-1
public class MyClass {
    public static void main(String args[]) {
        class MyClassA {
    
        private String name = "testA";
        
        
        public String getName() {
            return name;
        }
        
        public void printName() {
            System.out.println(this.getName());
        }
    
    }

    class MyClassB extends MyClassA {
    
        private String name2 = "testB";
    
        public String getName() {
            return name2;
        }
        
        public void printName() {
            super.printName();
            System.out.println(getName());
        }
    }
    
      MyClassA classA = new MyClassA();
      MyClassB classB = new MyClassB();

      System.out.println("Print name in A:");
      classA.printName();
      System.out.println("Print names in B:");
      classB.printName();
    }
}

Output is:

Print name in A:
testA
Print names in B:
testB
testB

My question is why it printed "testB" both times in the end. I would have expected it would be "testA testB" because the first "printName" in MyClassB called the super method.

Is it possible to make it work so that it prints "testA testB"?

kinglite
  • 339
  • 3
  • 20
  • 3
    Your `classB` variable is a instance of `MyClassB` which overrides `getName`. Since it's overridden, the superclass will call the instance method too – Tidemor Mar 30 '22 at 13:50
  • 1
    That is how Java works. Which method is called does not depend on where the code resides; it depends on the runtime type of the object. Calling `getName()` on an instance of MyClassB will *always* invoke the MyClassB implementation. That includes every printName method in every class. – VGR Mar 30 '22 at 15:47

1 Answers1

0

To make the output print "testA testB", you have to avoid overriding the getName() method.

A simple fix would be to change the name of one method, if the getName() method of MyClassB was changed to getName2() as follows,

class MyClassB extends MyClassA {

    private String name2 = "testB";

    // change name here
    public String getName2() {
        return name2;
    }
    
    public void printName() {
        super.printName();
        System.out.println(getName2());
    }
}

you will get the desired output. Checkout these rules for method overriding for further reference.

Halo
  • 1,730
  • 1
  • 8
  • 31
strz3lmno
  • 51
  • 5