Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

abstraction in java program

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();
    }
}
like image 940
user260833 Avatar asked Dec 24 '22 03:12

user260833


2 Answers

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();

like image 66
user7294900 Avatar answered Jan 10 '23 22:01

user7294900


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.

like image 35
Aminu Bishir Avatar answered Jan 10 '23 21:01

Aminu Bishir