Inheritance
/**
* Inheritance means that a subclass extends a super class.
* Superclasses defines what subclasses have in common then abstract those features.
*
* Every class in Java extends class Object.
* Object is the only class that has no superclass.
*/
package com.minte9.oop.inheritance;
public class Inheritance {
public static void main(String[] args) {
Dog d = new Dog();
d.setAction("barking");
Bird b = new Bird();
b.setAction("flying");
d.doAction(); // The dog is barking
b.doAction(); // The bird is flying
}
}
abstract class Animal {
public String action;
public void setAction(String s) {
action = s;
}
public abstract void doAction();
}
class Dog extends Animal { // Look Here
@Override
public void doAction() {
System.out.println("The dog is " + action);
}
}
class Bird extends Animal {
@Override
public void doAction() {
System.out.println("The bird is " + action);
}
}
Abstract Keyword
/**
* By making the superclass abstract we prevent instantiation.
*
* What exactly is a Pet object, what color, what size?
* We don't know (the class must be declared as abstract).
*
* An abstract class can be extended.
* An abstract method must be overrided.
*/
package com.minte9.oop.inheritance;
public class AbstractKeyword {
public static void main(String[] args) {
MyDog myDog = new MyDog();
myDog.setColor("gray");
System.out.println(myDog.color); // gray
}
}
abstract class Pet {
protected String color;
public abstract void setColor(String c); // abstract method
public void setName() {} // non-abstract method (body)
}
class MyDog extends Pet {
public MyDog() {}
public void setColor(String c) {
this.color = c;
}
}
Override Annotation
/**
* Override annotation acts as a compile-time safeguard.
* Abstract method with no Override will throw error only at compile time.
*/
package com.minte9.oop.inheritance;
public class OverrideAnnotation {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.settName();
}
}
abstract class MyAbstractClass {
abstract public void setName();
}
class MyClass extends MyAbstractClass {
@Override
public void setName() {} // Correct - with Override
// ... Add another method later:
// Wrong name and no Override annotation for safeguard.
public void settName() {
System.out.println("Wrong method called!");
}
}
Questions and answers:
Clink on Option to Answer
1. What does inheritance mean in Java?
- a) A subclass extends a superclass and inherits its features
- b) A superclass extends a subclass
2. Why can’t an abstract class be instantiated?
- a) Because it has the abstract keyword
- b) Because it has no variables
3. What is the main purpose of the @Override annotation?
- a) It acts as a compile-time safeguard
- b) It makes the method run faster
4. What must a subclass do with an abstract method?
- a) Ignore it
- b) Override and implement it