Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 379
LAT Avatar asked Apr 12 '10 13:04

LAT


2 Answers

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!
like image 186
Hardcoded Avatar answered Nov 12 '22 22:11

Hardcoded


p is both a Student and a Person but if you call a method (like whoAreYou()), Java will first try to find it in Student and then in Person.

like image 26
Aaron Digulla Avatar answered Nov 12 '22 22:11

Aaron Digulla