Leonard Shin
Leonard Shin

Reputation: 51

How does super work in the case of the code below? (java)

public class Magenta
{
    public void m3()
    {
        System.out.println("Magenta 3");
        m2();
    }
    public void m2()
    {
        System.out.println("Magenta 2");
    }
}
public class Yellow extends Magenta
{
    public void m1()
    {
        System.out.println("Yellow 1");
        super.m2();
    }
    public void m2()
    {
        System.out.println("Yellow 2");
    }
}
public class Key extends Yellow
{
    public void m2()
    {
        System.out.println("Key 2");
    }
}

Why is it that if I construct a Key object

(Using Yellow var1 = new Key();) and

call m1();,

why doesn't it print Yellow1\nYellow2? Instead it prints Yellow 1\nMagenta 2,

which suggest that the call to super on the Key object is actually not called on the Key object.

I'm confused as to how super works here I thought it'd make it be interpreted as key's superclass,

which is Yellow, would be calling m2();.

Upvotes: 3

Views: 68

Answers (3)

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

When you are calling m1() on a Key instance, the method m1 of class Yellow is called as it is inherited by the Key class and not overridden inside it.

So if you look inside m1() of Yellow, it will first print "Yellow 1" and then it will call the superclass Magenta's method m2() which will print "Magenta 2".

Here is a visualization:

enter image description here

Upvotes: 3

Chetan Joshi
Chetan Joshi

Reputation: 5721

Super keyword denotes object of Super Class ,

So when you call super.m2() its calls goes to Super class method m2();

if you call m2() method of yellow class simply call m2() without using super.

Super Keyword in Java

The super keyword in java is a reference variable that is used to refer parent class objects.

Use of super with variables: This scenario occurs when a derived class and base class has same data members.

Use of super with methods: This is used when we want to call parent class method.

Upvotes: 0

Andronicus
Andronicus

Reputation: 26076

You;re instantiating an object of class Yellow and calling m1 method. This works as follows:

System.out.println("Yellow 1");
super.m2();

So it prints "Yellow 1" and calls m2 of superclass, which is Magenta, so:

System.out.println("Magenta 2");

Upvotes: 2

Related Questions