PROGRAMMING

MINTE9
REMEMBERS




Last update:   23-07-2021

Polymorphism

p213 ! The reference and the object can be different. But you can't access the methods if they are only in sublcass.
 RunCode
class LearningApp {
    public static void main(String[] args) {

        Animal[] animals = new Animal[2];

        animals[0] = new Dog(); // reference is an Animal
        animals[1] = new Cat(); // object is a Cat

        animals[0].roam(); // myDgog is roaming
        animals[1].eat(); // myCat is eating
        animals[0].bark(); // Error: cannot find symbol - Look Here

        ((Dog) animals[0]).bark(); // myDog is barking
    }
}

class Animal {
    protected String name;
    public Animal() {}
    public void eat() { System.out.println(this.name + " is eating"); }
    public void roam() { System.out.println(this.name + " is roaming"); }
}

class Dog extends Animal {
    public Dog() { this.name = "myDog"; }
    public void bark() { System.out.println(this.name + " is barking"); }
}

class Cat extends Animal {
    public Cat() { this.name = "myCat"; }
}
... 18 lines
˄˄˄

Parameter

! You can declare the method parameter as a super-class type.
 RunCode
class App {
    public static void main(String[] args) {

        Vet v = new Vet();
        Cat c = new Cat();

        v.giveShot(c); // cat is Animal type
    }
}

class Vet {
    public void giveShot(Animal a) { a.makeNoise(); }
}

class Animal {
    protected String name;
    public Animal() {}
    public void makeNoise() { System.out.println(this.name + " make noise"); }
}

class Cat extends Animal {
    public Cat() { this.name = "cat"; }
}
... 12 lines
˄˄˄

Questions    
11. Static
10 . Polymorphism
Last update:   23-07-2021

        A B C D E F
🔔
1/2