Java Inheritance forces me to do what I don’t need when super () is called

I read the official Java tutorials on the Oracle website and I don't like what I see when experimenting with Inheritance.

I created the Bicycle class and the MountainBike class, which extends the bike. MountainBike is forced to call super () on the Bicycle constructor from its own constructor, but this is what happens:

A Bicycle has been created.
A Bicycle has been created.
A MountainBike has been created.

When the classes look like this (snippet):

public Bicycle(int speed) {
 this.speed = speed;
 System.out.println("A Bicycle has been created.");
}

public MountainBike(int seatHeight, int speed) {
 super(speed);
 this.setSeatHeight(seatHeight);
 System.out.println("A MountainBike has been created.");
}

This is an undesirable behavior.

  • Is this a common lack of inheritance?
  • What are you doing in this case?
+3
source share
2 answers

? MountainBike Bicycle, "A Bicycle ". , "A MountainBike ". .

, , "A Bicycle ". MountainBike, Bicycle MountainBike , , . , , - , MountainBike is a Bicycle.

public class BikeWarehouse {

    public Bicycle buildBicycle(int speed) {
        Bicycle bicycle = new Bicycle(speed);
        System.out.println("A Bicycle has been created.");
        return bicycle;
    }

    public MountainBike buildMountainBike(int seatHeight, int speed) {
        MountainBike mountainBike = new MountainBike(seatHeight, speed);
        System.out.println("A MountainBike has been created.");
        return mountainBike;
    }
}

toString() Bicycle MountainBike, , , :

System.out.println("A " + bike + " has been created");

, toString() Bicycle "Bicycle", toString() MountainBike "MountainBike".

, , - , ( "" ), , - AspectJ. , , , - .

+4

:

  • . . : -)

  • 'System.out.println( "A XXX ." )' System.out.println.

+1

Source: https://habr.com/ru/post/1777364/


All Articles