-5

I have a Person class, and Object class is just the Object class of Java. I have a Student class that extends the Person Class as well. Can somebody explain why in these different scenarios I get errors when casting and some work?

Person p = (Person) new Object(); // error
Person p = (Person) new Student(“Steve”, 21, 12345); // works
Object o = new Person(“Steve”, 21); // works
Person p = (Person) o; // works
dppham1
  • 117
  • 1
  • 9

3 Answers3

2

Casting doesn't magically turn an object into something else. It just tells the compiler to attempt to access a piece of data as a different type.

In the first example, you create an Object, which can't be cast into Person. Casting does not magically transform things.

In the second example, you create a Student object. Since Student inherits from Person, you can also consider it of type person.

Line 3: Again, you create a Person object but you hold it in a variable of type object. That doesn't change what the object actually is, which is why the downcasting to Person works.

Jochen Bedersdorfer
  • 4,093
  • 24
  • 26
0

Object class is Base Class of all java classes ,That's why reference of Object capable to hold object of any java class .

But if any class extends another class then child class not directly extends Object class in this case multilevel Inheritance concept implements implicitly .

In Your case

Person class is super class ,

Student class is sub class.

That's means Student class acquire properties of Person class , Casting is possible in this case as wall as Student extends Object class through Person Class.

Chetan Joshi
  • 5,582
  • 4
  • 30
  • 43
0

It's OK to cast a child(sub) class object to a parent(super) class because child class already know and has everything(ie. variables and methods) from the inheritance of parent class, but not the other way around.

Example:

Parent class has method a1().
Child class added a method a2().
Child automatically gets a1() through inheritance.
Parent knows nothing about a2().
ndlu
  • 161
  • 1
  • 9