Why is the output like below?
bike is created
running safely..
gear changed
because we are not calling Bike()
method anywhere.
abstract class Bike {
Bike() {
System.out.println("bike is created");
}
abstract void run();
void changeGear() {
System.out.println("gear changed");
}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike {
void run() {
System.out.println("running safely..");
}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2 {
public static void main(String args[]) {
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
Honda class is created with Default Constructor
If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.
public class Point { int x, y; }
is equivalent to the declaration:
public class Point { int x, y; public Point() { super(); } }
So Bike()
is called every call to new Honda();
In he Bike class, you have a constructor Bike() that prints a statement. So by default, a child class build upon the constructor of its parent class. That's why when ever you create an object of the class Bike, the print statement has to appear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With