Quick JAVA inheritance question
if I have an abstract class named Dog with开发者_开发百科 a constructor to set its weight (double) and a class named SpecialDog which extends Dog and has a constructor that accepts a double and passes it to Dog using super().
What (if any) are the differences between:
Dog dog = new SpecialDog(12.0);
SpecialDog dog = new SpecialDog(12.0);
Dog dog = new Dog(12.0);
SpecialDog dog = new Dog(12.0);
Thanks!
To answer your questions (they are all different):
Dog dog = new SpecialDog(12.0);
Here, you are creating a SpecialDog, but using a Dog reference to point to it. The object is a special dog, but, unless you downcast your dog
variable, you are only going to be able to treat dog
as a Dog
and not a SpecialDog
.
SpecialDog dog = new SpecialDog(12.0);
Here, you are creating a SpecialDog, and using a SpecialDog reference to point to it.
Dog dog = new Dog(12.0);
This is a compiler error since you can't instantiate abstract classes.
SpecialDog dog = new Dog(12.0);
This is just a compiler error. You can't assign a super class to a sub class reference. Remember: inheritance is a "is-a" relationship. While a SpecialDog is always a Dog, a Dog might not always be a SpecialDog.
If your Dog
class is abstract then
Dog dog = new Dog(12.0);
SpecialDog dog = new Dog(12.0);
will not compile.
To answer a question in your comment:
If you use Dog
variable you will only be able to use methods of Dog
class.
Compiler will generate an error if you would try to use methods of the SpecialDog
in this case.
The use of Dog dog = new SpecialDog(12.0);
promotes polymorphism in your code. In another word, it promotes extendability in your APIs in the future.
For example, if your method accepts Dog
as a parameter, then any dog can be passed into that method:-
// you can pass SpecialDog, SkinnyDog, UglyDog into this API to make the dog fat
public void makeMeFat(Dog dog) {
...
}
However, if the method accepts only certain type of dog, then only that dog can be used in that method:-
// you can only pass SpecialDog into this API
public void makeMeFat(Special dog) {
...
}
If you make Dog
to be an abstract class, then you cannot use it to create another Dog because an abstract class has only partial implementation. So, it is not possible to create a dog with an abstract class. In real world, you might get a dog with 3 legs with an abstract Dog
... but at least in the programming world, you get a compilation error because the compiler God doesn't want a 3-legged dog. :)
Create a SpecialDog, assign it to a Dog variable, you need to cast if you want to use SpecialDog only functions.
Dog dog = new SpecialDog(12.0);
Create a SpecialDog and assign it to a SpecialDog variable. Nothing special.
SpecialDog dog = new SpecialDog(12.0);
The remaining two try to create instances of an abstract class, and will not compile.
精彩评论