200 likes | 443 Views
Polymorphism Idea. The basic principle and aims of the generality and abstraction are: Reuse Interoperability The basic idea: A programmer uses a single, general interface, Java selects the correct method. Polymorphic Methods.
E N D
Polymorphism Idea The basic principle and aims of the generality and abstraction are: Reuse Interoperability The basic idea: A programmer uses a single, general interface, Java selects the correct method.
Polymorphic Methods • A method is polymorphic if the action performed by the method depends on the actual type of the object to which the method is applied. • In OOP calling a method is often referred to as sending a message to an object. At runtime, the object responds to the message by executing the appropriate method.
Polymorphism • System.out.println(p); • is a message to the object referred to by p (Which message?): • If an Object is referenced by p, then toString method of Object class is invoked • If a Point is referenced by p, then toString method of Point class is invoked. • If ColoredPoint is referenced by p, then toString method of ColoredPoint class is invoked.
Static Methods • When we invoke a method on an object we always do it through a reference? • Static methods can be invoked using a class name! (but can also using a reference) • They are resolved at compile time, when we do not know which type of object is actually referenced. Therefore they depend on the type of reference.
Instanceof Operator • You can restore the narrow point of view for objects, by using casting. • However at runtime you must know the true type of object referenced by some wider (base) reference (why?). • The instanceof operator can be used to query about the true type of the object you are referencing.
Rules of Casting • Casting let us restore a more specific point of view of an object. • Casting a reference should be done only after verifing the object is indeed of the type we cast to! • You cannot refer to an object through a Point reference unless this object is indeed a Point object! • If we try to cast a Point reference referring to a regular Point object, into a ColoredPoint, a ClassCastException will be thrown. Point p = new Point(); ColoredPoint cp = (ColoredPoint )p;
Casting example class Parent {} class Child extends Parent {} class Uncle {} class Test { public static void main( String args[] ) { Object object; Parent parent; Child child = new Child(); Uncle uncle; parent = child; object = child; parent = (Parent) object; child = (Child) object; uncle = (Uncle) object; parent = (Parent)child; parent = new Parent(); child = (Parent)child; parent = (Child)parent; Object o = (Parent)child; parent = new Child(); Parent p = (Parent)parent; Child c = parent; } }
Abstract Classes • We would like to describe abstract data types as classes. We use an abstraction which can sometimes be so general, that without filling the gaps it would make no sense to create an object from the class. • Shape, Animal, Vehicle ….
Abstract Classes • We would like to prevent the user from creating an object that makes no sense. • This can be accomplished by making all the methods print error messages, but that delays the information until run-time and requires reliable exhaustive testing on the user’s part. • It’s always better to catch problems at compile-time.
Abstract Classes • The java language allows a class designer to specify that a super class declares a method with no implementation. • A method with a missing implementation is called an abstract method as opposed to a concrete method with an implementation • The syntax of an abstract method is : abstract void foo();
Abstract Classes • A class with one or more abstract methods is called an Abstract class. The class must be qualified as abstract ,otherwise, the compiler gives you an error message. • A class which implements all its methods is a concrete class. • Note that you can define a class to be abstract although it has no abstract methods but this is done in rare cases.
Abstract Classes • The implementation of an abstract method must be supplied by a concrete sub class of the abstract class • The java compiler prevents the programmer from instantiating an abstract class • However the abstract class may have some concrete methods as well as constructors and attributes
Animals • An animal defines a group of living things animals do have common features, but an instance of an animal does not male sense unless we fill the define the concrete feature of specified object. • Animals eat, move and reproduce
Abstract Animal /** * An Animal represents a living animal that can * reproduce, eat and move */ public abstract class Animal { protected int numberOfLegs; /** * Constructs a new Animal with a given number of legs */ public Animal(int numberOfLegs) { this.numberOfLegs = numberOfLegs; } public abstract void eat(); public abstract Animal reproduce(); /** * move the animal */ public void move() { System.out.println(" this aniamal is moving with it's " + numberOfLegs + "legs"); } }
Pets Pets are animals that human keep. A pet can be named and played with. Still this definition is somewhat general and A pet instance may not make sense. public abstract class Pet extends Animal { protected String name; /** * Constructs a new Pet with a given number of legs * and a given name */ public Pet (int numberOfLegs, String name){ super(numberOfLegs); this.name = name; } public void setName(String name){ this.name = name; } public String getName(){ return name; } public abstract void play(); }
Animal Hierarchy Animal Pet Spider Dog Cat
Vector • One of the most useful classes in the Java API is java.util.Vector. • A vector is an ordered collection of objects. • You may add or remove objects from the vector at any position and its size grows and shrinks as needed to accommodate adding and removing items.
Cats & Dogs… • class Cat { • public String toString() { • return new String(“meaw”); • } • } • class Dog { • public String toString() { • return new String(“bark”); • } • } • class Mouse { • public String toString() { • return new String(“squeak”); • } • }
Using a Vector class MouseTrap {public static void main(String[] args) { Vector v = new Vector(); v.addElement(new Cat()); v.addElement(new Mouse()); v.addElement(new Dog()); v.addElement(new Mouse()); v.addElement(new String(“its raining”)); for (int i = 0; i < v.size(); i++) System.out.println(v.elementAt(i)); catchTheMice(v); } private static void catchTheMice(Vector v) { int i = 0; while (i < v.size()) { if (v.elementAt(i) instanceof Mouse) { v.removeElementAt(i); } else { i++; } } }
The Vector Holds Object References “a string” Object Mouse String Cat Dog