Creating subclass instances from the base class constructor

I am learning OOP with Java. Let's say I have a base class car with subclasses that extend the car called Engine, FuelTank and Wheels. Is it possible to create these extended classes from the base Car class so that each car instance has its own instance of each subclass?

class Car{
      Car(){
          // instance of Engine
          // instance of Wheels
          // instance of FuelTank
      }
 }

class CarPart{}

class Engine extends CarPart{}

class Wheels extends CarPart{}

class FuelTank extends CarPart{}
+4
source share
3 answers

Your question:

Can I instantiate other classes inside a class?

Well, theoretically and technically, you can easily get a yes answer. But the real answer is no. Because if you do this:

  • , (Car) , (Engine, Wheels, FuelTank). , , .
  • , , . -... "" - .

, "" . , : , .

, : , . , . . (DI). - - . , , . , . - , : - .

, : Engine CarPart. , , . Wheels FuelTank. , -:

class Engine {...}
class Wheels {...}
class FuelTank {...}

class CarEngine extends Engine {...}
class CarWheels extends Wheels {...}
class CarFuelTank extends FuelTank {...}

, :

class Car{

    Car(instance of CarEngine, instance of CarWheels, instance of CarFuelTank){
        //...
    }

}

, , :

class Car {

    Car(instance of Engine, instance of Wheels, instance of FuelTank){
        //...
    }

}

, :

!


1:

@Ryan The Leach / factory. .

. ? : factory. factory.

factory - , : ( ?). , . , factory , , , " ()".

, factory / / . factory: factory, factory factory. .

, , factory:

  • factory
  • factory
  • factory.

, () -, :

P.S:

... :-) , , ? , , . : : . Nota bene: , "Head First Design Patterns".

+4

, , .

public class Base {
     public void someMethod(){
         Child child1 = new Child(); // valid
         Base child2 = new Child(); // valid
    }
}

public class Child extends Base{

}

OOPs: .

B A , B A .

, . , . ( Open closed). , , . , , , , , . prqctice, . . . composition inheritence.

Car Wheel, Engine ..

, Wheel, Engine, Car . , Wheel (, NormalWheel, AlloyWheel) , Car. , .

+2

.

, . .

Sub . Car - , SportCar, , RacingCar ..

, SportCar - Car, , .

Is-A Relationship.

"" - " " .

, ......

0

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


All Articles