Can I create an extention of a class that is already an extention of another class?

77 Views Asked by At

I have a class called Car, and an extention of Car, called Mazdamx5. Can I create a class that extends Mazdamx5 that contains the properties of Car, but also contains the modified or overridden properties of Mazdamx5, or will this only cause complications? Oh, yeah, forgot the important part. How do I do all this with Car and Mazdamx5 in a different package than my new extention? By import?

2

There are 2 best solutions below

2
On BEST ANSWER

You can certainly have class hierarchies like this, but you should consider your design implications a bit closer. Having deeply nested inheritance like that isn't necessary in a lot of cases.

If you want each class to have shared fields, then use protected instead of private for their declaration.

This is entirely legal:

public class Car {

}

public class Mazdamx5 extends Car {

}

public class SomeOtherCar extends Mazdamx5 {

}
1
On

Try it out. Perfectly valid to create another class that extends Mazdamx5.

I provide the code example

class Car{
     void carDrive() {
         S.O.P("car drive");
     }
}
class Mazdamx5 extends Car{
      void drive() {
         S.O.P("drive 2");
       }
  }
 class Car2 extends Mazdamx5 {
      void drive() {
          S.O.P("Car 2 drive");
       }
 }

In this case, this class Car2 extends Mazdamx5, overrides method properties of Mazdamx5(drive method), and contins method properties of car(carDrive)