0

In this situation, do I have access to the overridden/additional methods of CarSubClass?

public Car getCar(){
CarSubClass carSub = new CarSubClass();
return carSub;
}

Update:

Car has subclasses SubClass1, SubClass2, SubClass3.

getCar() can return SubClass1,SubClass2, OR SubClass3.

Can I do this?:

Car car = getCar();

switch(car.getType()){//getType() returns a byte

case SubClass1:

SubClass1 car1 = (SubClass1)car;
break;

case SubClass2:
SubClass car2 = (SubClass2)car;
break;

case SubClass3:
SubClass3 car3  =(SubClass3)car;
break;

default: //don't do anything

}
3
  • What is c in your switch, from which you get the type? Commented Aug 1, 2013 at 14:07
  • Frequent downcasting is sometimes an indicator of poor OOP design. You may want to check out discussions of favoring composition over inheritance, e.g. artima.com/lejava/articles/designprinciples4.html Commented Aug 1, 2013 at 14:14
  • Sorry, c was supposed to be car. It has since been fixed Commented Aug 1, 2013 at 14:36

3 Answers 3

1

Only overriden methods :

Car car  = getCar();
car.method(); // here you can invoke only the overridden methods in CarSubClass

You cannot call the additional methods of CarSubClass which the reference type Car has no knowledge of. It will fail during compilation itself.

Probably this is possible , but you must be certain what you are doing here :

CarSubClass c = (CarSubClass)getCar();
c.subClassSpecificMethod();

The above casting is safe in your case because the method always returns an instance of CarSubClass . It is better to perform a check though.

Car c = getCar();
if(c instanceof CarSubClass){
    ((CarSubClass)c).subClassSpecificMethod();
}

switch(c.getType())

That is not a valid switch key.

JLS§14.11:

The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (§8.9), or a compile-time error occurs.

Sign up to request clarification or add additional context in comments.

4 Comments

So let's say that I have a bunch of different subclasses to car, is there any way I can return a car and then cast that car to whatever type of car it is? Do I do that in the get method or in the place where getCar is called?
Is what you just added work with what I posted in my update? I believe it is the same(I typed my update before i saw your response)
Okay, I didn't write that c.getType() returns a byte. Thank you for the help :)
You don't need to cast actually, see my response. You are mentioning that the methods are overridden, hence you will not get a compilation failure if you don't cast.
1

Yes, through dynamic typing/calls it will be available. This is the whole purpose of polymorphism.

But since you are returning a Car instance, whichever class that calls 'getCar()' must cast it to a 'CarSubClass' first.

Car.java

public class Car {

public void a() {
    System.out.println("In Car");
}

}

CarSubClass.java

enter code herepublic class CarSubClass extends Car {

@Override
public void a() {
    System.out.println("In CarSubClass");
}

public static void main(String[] args) {
    Car c = new CarSubClass();
    c.a();
}

}

Will output:

'In CarSubClass'

Edit: I have edited my answer. This whole concept is called polymorphism. You are not required to cast, since at runtime, the dynamic type the variable holds, will ensure that the correct method is called.

2 Comments

So let's say that I have a bunch of different subclasses to car, is there any way I can return a car and then cast that car to whatever type of car it is? Do I do that in the get method or in the place where getCar is called?
I have edited my answer. This whole concept is called polymorphism. You are not required to cast, since at runtime, the dynamic type the variable holds, will ensure that the correct method is called.
0

Not unless you cast it to CarSubClass. See below as an example (a really bad one though):

public class Test {

    public static Car getCar() {
        return new SmallCar();
    }

    public static void main(String[] args) throws Exception {
        ((SmallCar) getCar()).getMake();
    }

    static class Car {

        String model;

        public String getModel() {
            return this.model;
        }
    }

    static class SmallCar extends Car {

        String make;

        public String getMake() {
            return this.make;
        }
    }
}

Best of luck...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.