0

So I have a Superclass and two classes ClassA and ClassB that extend Superclass. ClassA and Superclass contain a method .doSomething(), ClassB does not. I got instances of ClassA and -B in a List<Superclass> objects. There also is a loop that iterates through objects and calls .doSomething() like this:

for(Superclass o : objects){
    o.doSomething();
}

My question is: If o is an instance if ClassA, is then ClassA.doSomething() being called or does this loop only call Superclass.doSomething()?

purpule
  • 116
  • 1
  • 10
  • If there was only a possibility to _simply try it_. Hint: `ClassA.doSomething()` is called. – Marvin Nov 04 '17 at 15:08
  • The overriden version will always be the one that's used, so yes, it'll be `ClassA.doSomething()` – user184994 Nov 04 '17 at 15:08
  • without seeing the code of ClassA, we cannot answer. – davidxxx Nov 04 '17 at 15:17
  • @davidxxx We cannot? What are you thinking of? – Marvin Nov 04 '17 at 15:20
  • @Marvin 1. we don't know whether `doSomething()` is actually overrided in `ClassA`. 2. If it is, we don't know whether the implementation also invokes the method of the super class. – davidxxx Nov 04 '17 at 15:22
  • @davidxxx 1. *"ClassA and Superclass contain a method .doSomething()"*, this statement tells us that `ClassA` has `doSomething` and it is therefore an overrode. 2. This is a valid point. Although, the question title should indicate that this corner case is not what the OP is asking for. – Chetan Kinger Nov 04 '17 at 15:25
  • #1 is IMHO clearly stated in the question and #2 doesn't change the fact that the loop does **not** _"only call `Superclass.doSomething()`"_. – Marvin Nov 04 '17 at 15:34
  • Your code will not even compile. – Raedwald Nov 05 '17 at 08:10

4 Answers4

1

Yes, because SuperClass implements doSomething, ClassB inherits that implementation, ClassA overrides it.

Robert Moskal
  • 21,737
  • 8
  • 62
  • 86
0

Yes, as the method .doSomething() of ClassA overrides the one of Superclass.

flogy
  • 906
  • 4
  • 16
0
  class Super
{
 void hi()
 {
 System.out.println("Super class");
 }
}
class A extends Super
{
 void hi()
 {
  System.out.println("Class A");
 }

}
class B extends Super
{


}
public class Drive
{

public static void main(String[]args)
{
 Super s=new A(); 
 s.hi();                // prints "Class A"
 Super h=new B();
 h.hi();             // prints "Super Class" since B does not override Super
}
}                        //hope this helps
Aishwarya
  • 110
  • 6
0

If an instance is of ClassA, then its method will be called, and superclass methods will only be consireded if ClassA doesn't have an implementation.

And this doesn't change if you assign the ClassA instance to a variable of a superclass type. In other languages, that might be different, but with Java it's always like that.

Ralf Kleberhoff
  • 6,990
  • 1
  • 13
  • 7