Monday, February 19, 2007

Lecture 15

Things to know for the next Lab:

Inheritance, Arrays, Interface

Things to know for the Midterm:


everything we have covered until this class (Feb 19 2007) is fair game for the midterm
this is unofficially true but the only thing Andrew has told pertaining to Test Content.


Aggregation
  • keeps a reference to an external object
  • external object outlives the aggregate
Composition
  • keeps a copy of object it contains
  • contained object lives and dies with the composition
Polymorphism and Arrays

public class Parent{}

public class Child extends Parent{}

Parent P;
Child c;
c = new Child();
p = c;

  • this is legal
  • P is a reference to C
  • P is of type parent
  • P is a reference to C and is treated like an object of type Parent
  • remember
    • C inherits all of P's methods
    • C can use anything inherited from P
      • public methods ...etc
  • but when p=c
    • p can only access inherited methods from C
      • in other words only methods which exist in both classes can be used in p
  • suppose C has an overridden method
public class Parent
{
public void myMethod()
{
System.out.println("parent");
}
}
public class Child extends Parent()
{
public void myMethod()
{
System.out.println("child");
}
}
-------------------------------------------------

Child c;
Parent p;
c = new Child();
p = c
c.myMethod(); /* prints "child" */
p.myMethod(); /* prints "child" */
  • p.myMethod prints "child"
    • this is because java remembers that P started out as C which is type child
      • this is called "Late Binding"
Summary

Child c;
Parent p;
c = new Child();
c.myMethod(); /* prints "child" because of overriding*/
p = c;
p.myMethod(); /* prints "child" because of polymorphism / late binding*/
p = new Parent();
p.myMethod(); /* prints "parent" because it is not an object reference anymore*/

No comments: