Back to GT CS-1331

Polymorphism:

  • The idea that an object can exist in different forms at the same time
  • Allows the processing of multiple objects from different classes without having to rewrite code specific for each class
//Example of Polymorphism 
className objectName = new className(); //Without Polymorphism
Object objectName = new className(); //With Polymorphism (Both a java.lang.object and className object)

Assignments, Methods, and Casting:

Declared type vs object type:

  • An object type must be a subclass of a declared type
Canine pixie; //Declared Type is Canine
pixie = new Wolf(); //Object Type is Wolf (Which is a subclass of Canine)

Accessing variables/methods from declared and object type:

  • An object can access all data from it declared type like normal
  • To access data from its object type, the object must be typecasted into its object type class
    • Creates a temporary reference
  • Compile-Time casting is also known as implicit casting
    • Is safe and can upcast or downcast
  • Runtime Casting is explicit casting
    • Only downcasting is allowed
    • Must be a legal downcast
Canine pixie;
pixie = new Wolf();
//Assume the Canine class has the method bark and Wolf has the method run
//Calling methods:
pixie.bark();
((Wolf)pixie).run(); //Typecasting from Canine to Wolf

Dynamic Binding:

  • Matching a method call in a statement to it actual definition at runtime
  • Also called late-binding and runtime resolution
  • If a method is called on an object, it will move up the inheritence tree and will call the first instance of that method that it finds