Inheritance and Polymorphism

inheriting instance methods and variables

  • privates: cannot be inherited or (methods) overridden

    • accessing: use an accessor or mutator method that is inherited

constructors

  • never inherited

  1. no constructor for subclass: calls default (no param) from superclass

    public subClass(){
    	super();
    }
  2. no constructor for subclass but constructor with param from superclass: compile error

  3. none of the above: compile error

public Student (String studName, String studGrade){
	name = studName;
	grade = studGrade;
}
/instance variables: only initiaize gradStudID

public gradStudent (String studName, String studGrade, int gradStudID){
	super(studName, studGrade); 
	studID = gradStudID;
}

super()

  • written in the first line of the constructor body

  • if no constructor or super(), default no param constructor

Polymorphism

Variable name = new Object();

think: Superclass name = new Subclass();

  • variable references the object type

    • ex. Cat c = new Tiger();

    • when I call c, it’s a tiger that should be able to do everything a cat can do (which is true)

    • c.sayHello();

    • c is a tiger, so the tiger says hello

a.method(b)

a=method selected @ run time

b=must be correct during compile time

  • compile: Superclass needs to have that method (won’t compile, won’t run otherwise)

    • declared as cat, so we look in Cat class but it can’t do everything a tiger can do

  • run: reads the object type and runs that method. If not, it will look in the superclass to run.

Note: Even if the actual type has the method, if it won’t compile, it won’t run.