Use super.display if overridden method display() of superclass Animal needs to be called.
xclass Animal {
public void display() {
System.out.println("I am an animal");
}
}
class Dog extends Animal {
public void display() {
System.out.println("I am a dog");
}
public void printMessage() {
display();
super.display(); // use super.display() to call the Animal class display() function
}
}
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.printMessage();
}
}
// ouput:
// I am a dog
// I am an animal
xxxxxxxxxx
class Animal {
protected String type = "animal";
}
class Dog extends Animal {
public String type = "mammal";
public void printType() {
System.out.println("I am a " + type);
System.out.println("I am an " + super.type);
}
}
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.printType();
}
}
// ouput:
// I am a mammal
// I am an animal
xxxxxxxxxx
class Animal {
Animal() {
System.out.println("I am an animal");
}
}
class Dog extends Animal {
Dog() {
super();
System.out.println("I am a dog");
}
}
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
}
}
// ouput:
// I am an animal
// I am a dog
xxxxxxxxxx
class Animal {
Animal() {
System.out.println("I am an animal");
}
Animal(String type) {
System.out.println("Type: "+type);
}
}
class Dog extends Animal {
Dog() {
super("Animal"); // transfer "Animal" to Animal(String type) this function
// super(); // if use super(), will be call the Animal() this function
System.out.println("I am a dog");
}
}
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
}
}
// ouput:
// Type: Animal
// I am a dog