I have two classes Animal and Dog. As you can quess dog extends from animal. I can write these classes with no problem but I noticed that I can create a new dog object like this:
Dog firstDog = new Dog("rocky");
It's ok, but when I try to create new instance like this:
Animal secondDog = new Dog("alex");
There isn't any error but I can't reach any fields or methods that I wrote in Dog class even if they are public so if I want to hold an object in a variable whose type is same with its super class's type, I can reach field and methods that implemented only that super class (for this example name, color, setColor() and toString()) and there isn't any way to reach fields and methods which implemented in subclass. Did I understand correctly also when I try to call toString() function of secondDog it calls the method that I wrote in Dog class, I know I override this function in Dog class but I can't reach other methods that I implemented in Dog class. How java handle these?
Animal Class:
public class Animal {
private String name;
private String color;
public Animal(String name){
this.name=name;
}
public void setColor(String color){
this.color=color;
}
public String toString(){
return"Hi, my name is " + this.name + ". I'm " + this.color;
}
}
Dog Class:
public class Dog extends Animal {
private int age;
public Dog(String name){
super(name);
setColor("gray");
this.age = 7;
}
public String speakDog(){
return"wof!";
}
public String toString(){
return super.toString() + " and I " + speakDog();
}
}