PROGRAMMING

MINTE9
REMEMBERS




Last update:   23-07-2021

ABSTRACT CLASS

p201 What exactly is an Animal object, what color, what size? By marking the class as abstract, you can prevent instantiation.
 RunCode
class LearningApp {
    public static void main(String[] args) {
        Dog d = new Dog("gray");
        Animal a = new Animal("nocolor"); // what color?
        System.out.print(a.color);
    }
}

class Animal {
    protected String color;
    public Animal(String c) {
        color = c;
    }
}

class Dog extends Animal {
    public Dog(String c) {
        super(c);
    }
}
... 12 lines
˄˄˄
 RunCode
class LearningApp {
    public static void main(String[] args) {
        
        Cat c = new Cat();
        
        Animal a = new Animal(); // Compile error
    }
}

abstract class Animal {}
class Cat extends Animal {}
... 2 lines
˄˄˄

Abstract method

p203 ! An abstract class means the class must be extended. An abstract method means the method must be overridden.
 RunCode
class LearningApp {
    public static void main(String[] args) {
        Dog d = new Dog();
    }
}
abstract class Animal {
    public abstract void eat(); // abstract
    public void setName(){} // non-abstract with {}
}

class Dog extends Animal {
    @Override public void eat() {}
}
... 6 lines
˄˄˄
Task

 CompleteTask
/**
 * Define abstact class Animal
 * Class Animal contains two methods, eat() and showName()
 * One of the method is abstract
 */

class LearningApp {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.setName("MyDog");
        System.out.println(d.name); // MyDog
    }
}

class Dog extends Animal {
    @Override
    public void eat() {}
}

...

solution code
Questions    
13. Interface
12 . Abstract
Last update:   23-07-2021

        A B C D E F
🔔
1/5