CS2312 Lecture 5
Inheritance and Scope
Inheritance:
Objects that are derived from other object "resemble" their parents by inheriting both state (fields) and behaviour (methods).
Parents are more general than children
Children refine parents class specification for different uses
Inheritance allows to write new classes that inherit from existing classes
The existing class whose properties are inherited is called the "parent" or superclass
The new class that inherits from the super class is called the "child" or subclass
Result: Lots of code reuse!
package test; public class Animal { public int numOfLegs; public Animal(int numOfLegs){ this.numOfLegs = numOfLegs; } public int getNumOfLegs(){ return this.numOfLegs; } public static void main(String args[]){ Dog xiaogou = new Dog(); Duck xiaoya = new Duck(); System.out.println("A dog has "+xiaogou.getNumOfLegs()+" and "+xiaogou.bark()); //A dog has 4 and Woof System.out.println("A duck has "+xiaoya.getNumOfLegs()+" and "+xiaoya.bark()); //A duck has 2 and Quack // Dog and Duck inherit the getNumLegs() method from the Animal super class, // but get bark and quack from their own class. } }
package test; public class Duck extends Animal{ public Duck(){ super(2); } public String bark(){ return "Quack"; } }
package test; public class Dog extends Animal{ public Dog(){ super(4); } public String bark(){ return "Woof"; } }
Use the extends keyword to indicate that one class inherits from another
The subclass inherits all the fields and methods of the superclass
Use the super keyword in the subclass constructor to call the superclass constructor
The first thing a subclass constructor must do is call a constructor in the superclass.
If the subclass constructor does not do this, then the default superclass constructor (with no arguments) will be called implicitly.
Inheritance defines an “is-a” relationship
- Dog is an Animal
- Duck is an Animal
One way relationship
- Animal is not a Dog! (Remember this when coding!)
The derived class inherits access to methods and fields from the parent class
- Use inheritance when you want to reuse code
When one class has a field of another class (or primitive type) - “has-a” relationship
- Animal has an int
package test1; public class A { public A(){ System.out.println("I am A"); } public static void main(String args[]){ C x = new C(); // I am A // I am B // I am C } }
package test1; public class B extends A{ public B(){ System.out.println("I am B"); } }
package test1; public class C extends B { public C(){ System.out.println("I am C"); } }
Overriding Methods
Subclasses can override methods in their superclass
package test2; public class Therm { protected double celsius; public Therm(double c){ celsius = c; } public double getTemp(){ return celsius; } public static void main(String args[]) { ThermUS the = new ThermUS(100); System.out.println(the.getTemp()); // 212.0 } }
package test2; public class ThermUS extends Therm{ public ThermUS(double c){ super(c); } public double getTemp(){ return celsius*1.8+32; } }
Casting
"Casting" means "promising" the compiler that the object will be of a particular type.– So the compiler should go ahead and convert
You can cast a variable to the type of the object that it references to use that object's methods.
Animal a1 = new Dog(); a1.bark(); //Animal does not have a bark method -> ((Dog)a1).bark(); //a1 change to Dog
((Duck)a1).quack(); //casting will fail, a1 is not a Duck
The casting will fail if the variable doesn’t reference an object of that type.
Example:
A company has a list of Employees. It asks you to provide a payroll sheet for all employees.
–Different types of employees
•manager, engineer, software engineer.
•Manager straight Salary
•Engineer Hourly
package test3; public class Employee { private String firstName,lastName; public Employee(String fName, String lName){ firstName = fName; lastName = lName; } public void printData(){ System.out.println(firstName+" "+lastName); } }
package test3; public class Engineer extends Employee { private double wage; private double hoursWorked; public Engineer(String fName, String lName, double rate, double hours){ super(fName,lName); wage = rate; hoursWorked = hours; } public double getPay(){ return wage * hoursWorked; } public void printData(){ super.printData(); System.out.println("Weekly pay: $"+getPay()); } }
package test3; public class Manager extends Employee { private double salary; public Manager(String fName, String lName, double sal){ super(fName,lName); salary = sal; } public double getPay(){ return salary; } public void printData(){ super.printData(); System.out.println("Monthly salart: $"+getPay()); } }
package test3; public class SalesManager extends Manager { private double bonus; // bonus = commission // A SalesManager gets a constant salary of $1250.0 public SalesManager(String fName, String lName, double b){ super(fName,lName, 1250.0); bonus = b; } public double getBonus(){ return bonus; } public void printData(){ super.printData(); System.out.println("Bonous Pay $: $"+getBonus()); } }
package test3; public class PayRoll { public static void main(String args[]){ Engineer fred = new Engineer("Fred","Smith",12.0, 8.0); Manager ann = new Manager("Ann","Brown", 1500.0); SalesManager mary = new SalesManager("Mary", "Kate",2000.0); Employee[] employees = new Employee[3]; employees[0] = fred; employees[1] = ann; employees[2] = mary; for (int i=0; i<3;i++){ employees[i].printData(); } System.out.println(ann instanceof Manager); //true System.out.println(ann instanceof Employee); //true System.out.println(ann instanceof SalesManager); //false System.out.println(employees[0] instanceof Employee); //true System.out.println(employees[0] instanceof Engineer); //true System.out.println(employees[0] instanceof Manager); //false } // Fred Smith // Weekly pay: $96.0 // Ann Brown // Monthly salart: $1500.0 // Mary Kate // Monthly salart: $1250.0 // Bonous Pay $: $2000.0 }
instanceof Operator
–returns true if an object is of the class
–returns true if an object is a subclass of the class
All Java classes implicitly inherit from - java.lang.Object
So every class you write will automatically have methods in Object such as equals, hashCode, and toString.
Scope