LAT LAT - 4 months ago 17
Java Question

Java inheritance and object casting

I am quite new to programming, i have a question please help me. ( this question is java question but i can't remember the syntax but what i write here is mostly it.)

A class Person speaks "i am a person"
A class Student speaks "i am a student"
Student extends from Person
Person p = new Student


then what is p speaking then?

Answer

p is just variable, it doesn't change the type of the Object that's in it.

You can think of a cup: You can put any fluid in it, but the cup won't change the type fluid.

abstract class Fluid{
  public String getTemp(){
    return "unknown";
  }
}
class Coffee extends Fluid{
  public String getTemp(){
    return "hot";
  }
}
class Cola extends Fluid{
  public String getTemp(){
    return "ice-cold"
  }
}

Fluid cup = new Coffee();
System.out.println(cup.getTemp()); //It's coffe in there, so it's hot!