- Objects that inherit features of a parent class can be thought to contain an object of the parent type
- all methods and fields of the parent are "inherited"
Best Practices With Inheritance
- discard packaging
- make all instance fields private
- this means instance fields are not visible to child methods
- if you need to access instance fields of the parent from the child use the public interface
Why Do This?
- child inherits parent's methods and therefore inherits the public interface
- this simplifies access
- and prevents privacy problems via inheritance
public class Parent
{
protected mutable class x;
}
public class Child extends Parent
{public mutable class leakyMethod()
{return m;
}
}
Constructors
- form part of the public interface
public class Child extends Parent
{
public child ( ...parameters for child / parent )
//call parent constructor
super(...parameters for parent)
//assigns child parameter
}
Overriding Methods
- Child classes inherit all methods from the parent
- child has the option to re-implement these methods
- called overriding
Example
- All objects extend type Object by default
public class MyClass [extends Object]
[
- type object contains several default methods
- equals(), toString(), clone()
- declaration of an overridden method in the child must be exactly the same as the parent
- same return type
- same parameter type
- same number of parameters
Parent
public int myMethod(double a, int b)
Child
public int myMethod(double a, int b)
- if myMethod is overridden in a child class, use 'super.myMethod' to gain access to the parent method
- to prevent overriding use 'final'
Abstract Classes
- a student is either graduate or undergraduate
- there is no 'plain' student
- so it doesn't make sense to instantiate this class
- all students have letter grades
- child classes of student should be forced to implement getLetterGrade()
Solution
- declare Student an abstract class
- can't instantiate an object of type student
- declare getLetterGrade() an abstract method within abstract class student
- children must override getLetterGrade() or they will be abstract classes themselves
public abstract class Student
{
.
.
.
public abstract String getLetterGrade();
}