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?
Asked
Active
Viewed 60 times
2 Answers
1
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 {
}

Makoto
- 104,088
- 27
- 192
- 230
-
isn't having the fields private better for encapsulation though? (protect private data, even in sub-classes?) – committedandroider Nov 11 '14 at 18:10
-
@committedandroider certainly yes. http://stackoverflow.com/a/3182664/995891 - also of interest for you: http://lassala.net/2010/11/04/a-good-example-of-liskov-substitution-principle/ whatever `extends Mazdamx5` must still be a Mazdamx5. If you want it to become a Ferrari, you're extending the wrong thing. – zapl Nov 11 '14 at 18:20
0
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)

committedandroider
- 8,711
- 14
- 71
- 126
-
Can anyone explain to me how i can make my answer better to not earn downvotes? – committedandroider Nov 11 '14 at 18:06