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
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