Reputation: 350
class Animal {
}
class Horse extends Animal {
}
public class Test {
public static void main(){
Animal a = new Horse();//mark1
}
}
Animal ah = new Horse();// reference type is Animal and object is Horse
I can't fully understand this below:
Animal ah = new Horse();// reference type is Animal and object is Horse
I always keep the reference type the same with the object
I want to know the reason of using the not-same reference type.Please tell me some condition that it's more appropriate to use it
Upvotes: 1
Views: 2927
Reputation: 26185
In addition to being able to have the same variable refer to objects of different classes during during a program execution, it is often done to keep coding options open.
The classic case is:
List<String> myList = new ArrayList<String>();
The compiler would reject e.g. myList.ensureCapacity(100) because ensureCapacity is not a List method. Only List methods can be used for myList. If, after the program is working and has been measured, it turns out that using a LinkedList would make the program faster, only the constructor call changes. Nothing is being done with myList that would not work with any List.
Upvotes: 2
Reputation: 2918
this works for several occasions, a simple example would be if you needed an array of animals:
Animal array[] = new Animal[3];
array[0] = new Horse();
array[1] = new Cow();
array[2] = new Animal();
You could have some defined generic methods or have them specified in for each class that extends.
public class Cow extends Animal {
public void sound() {
System.out.println("MOO");
}
}
public class Horse extends Animal {
public void sound() {
System.out.println("HEEEHREHE");
}
}
While in Animal you could not know the thing to do, so you could use somthing like
public class Animal {
public void sound() {
System.out.println(".");
}
}
The thing is that if you go throug every animal in your array it would use the method defined for it.
for (int i = 0; i < 3; i++) {
array[i].sound();
}
would output:
HEEEHREHE
MOO
.
Upvotes: 3
Reputation: 7964
As such you can use any of Animal or Horse as 'ab' type. In this particular case the usefulness of referring the object by Animal type lies in the fact that at later stage when you want to have ah point to some other animal object say Dog(which implement Animal interface) then at other places of code you will not need to make changes as at other places in code its still Animal type. So referring an object reference by an interface type gives liberty in changing the actual implementation instance dynamically and it kind of hides the implementation class from outside world as well.
Upvotes: 0