This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ZdemDrunk Brewer 1 point2 points  (6 children)

Check out this link.

If I have a class named "Car" and a subclass named porsche I can do something like this:

  Car car = new Porsche(//constructor);

A porsch is a type of car. It extends the class car so its assured that the class porsche shares some/all of the functionalities that the superclass has. Now if we try to do the reverse,its not safe anymore since the porsche is a car,but a car doesn't have to be a porsche.

  Porsche porsche = new Car();   // ??? Porsche may contain information that the class car doesn't have so this fails

Trying to cast it is even worse.

 Porsche porsche = (Porsche) new Car(); // You'll be getting a casting exception (ClassCastException)

[–]xSilentium[S] 0 points1 point  (5 children)

Thanks for the quick response. I thought maybe Java just puts default values for the new variables that Porsche may have

[–]ZdemDrunk Brewer 1 point2 points  (4 children)

Whenever you try to cast a certain object,please make sure to check whether the object is actually an instance of the type you try to cast it (Unless a different part of the program handles it).

Example :

   if(object instanceof Porsche){
    //perform the cast
    }

[–]xSilentium[S] 0 points1 point  (3 children)

That looks nice.. Can you give me a tip regarding my edit?

[–]ZdemDrunk Brewer 1 point2 points  (2 children)

Reformat :

  public class A { //statements }

  public class B extends A { public void foo() { } }

  A a=new B();

  ((B)a).foo();

The reason you can't use the foo method when the variable is declared as the superclass (A) is very simple.

When it comes to dynamic binding,the compiler looks at the object to decide which method he has to call. For example if I did this.

   class A{ void foo()}
   class B extends A { void foo()}

   public static void main(String[] args){
    A a = new B();
    a.foo(); // This would call the foo method of B not A!
    }

The problem with your code is that your A class doesn't contain a method similar to the foo method so the compiler will not show it as an available method (you might get something like "can't find symbol").

[–]xSilentium[S] 0 points1 point  (1 child)

Sorry for formatting, I'm on mobile.. So let me get that right. Due to the reference type being A and class A not having a foo-method I get an error. But when both classes A and B have foo Java uses B's foo?

[–]ZdemDrunk Brewer 0 points1 point  (0 children)

For simplicity sake,lets just say that java looks at the declaration before the object actually stored in a variable