Reputation: 43
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();
}
}
Upvotes: 4
Views: 624
Reputation: 1
you have created Honda class with a default constructor(without any formal arguments),so whenever you will make Honda class object then this will call default constructor(Honda()) and this constructor will call the parent class(Bike) default constructor and parent class constructor will print the statement "bike is created".
Upvotes: 0
Reputation: 111
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.
Upvotes: 3
Reputation: 58882
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();
Upvotes: 7