3. Inheritance and polymorphism

Created Friday 20 March 2015

http://home.cogeco.ca/~ve3ll/jatutor4.htm

Inherit

public class GraphicsBox extends Box

Override

Just create a method with the same name as in the parent

Call parent constructor and method

GraphicsBox(l,w,h,left,top) // constructor
{
super (l,w,h);
this.left=left;
this.top=top;
}
public void showObj()
{System.out.println(super.showObj()+"more stuff here");}

final methods, methods in final classes, private methods or static methods can't be overridden.

Interfaces

public interface Working
{
public void work();
}

public class WorkingDog extends Dog implements Working
{
public WorkingDog(String nm)
{
super(nm); // builds ala parent
}
public void work() // this method specific to WorkingDog
{
speak();
System.out.println("I can herd sheep and cows");
}
}

Polymorphism

3 types of polymorphism

  1. Ad-hoc
    1. Overloading
    2. Overriding
  2. Parametric
    1. Generic typing
  3. Dynamic (late) method binding
    1. Inheriting classes implement abstract methods in their own way — these methods will be resolved at runtime

Destroying

void finalize()
{
//cleanup code goes here
super.finalize() //parent too!
}

Arrays of objects

public class AnimalArray
{
public static void main(String args[])
Animal ref[] = new Animal[3]; // assign space for array
Cow aCow = new Cow("Bossy"); // makes specific objects
Dog aDog = new Dog("Rover");
Snake aSnake = new Snake("Stephen");

// now put them in an array
ref[0] = aCow; ref[1] = aDog; ref[2] = aSnake;

// now demo dynamic method binding
for (int x=0;x<3;++x) { ref[x].speak(); }
}

Casting objects

One of the difficulties of using a superclass array to hold many instances of subclass objects is that one can only access properties and methods that are in the superclass (ie. common to all). By casting an individual instance to its subclass form, one can refer to any property or method. But first take care to make sure the cast is valid by using the instanceof operator.

if (ref[x] instanceof Dog) // ok right type of object
{
Dog doggy = (Dog) ref[x]; // cast current instance to subclass
doggy.someDogOnlyMethod();
}



Backlinks: