简体   繁体   中英

Superclass method is called from subclass object

I have two classes SuperClass and SubClass,

class SuperClass{ public void count(){} }
class SubClass extends SuperClass { }
class Test
{
    public static void main(String[] args)
    {
        new SubClass().count();
    }
}

Here I used jdb to see how this code works, after making the Object of the SubClass, I expected the count method of the SubClass to be called as its inheriting the count method of the SuperClass, but the count method of SuperClass is being called.

I checked using "list" in jdb and it shows the line at count method of the SuperClass, why is this happening?

When you call an object's method, Java checks that the method exists in the object. If so, it calls it, otherwise it checks for the existence in the parent class. And so on until method is found. Since you haven't overridden your method, the one which is called is the parent one.

It should be something like below .

        class SuperClass{ public void count(){
    //if it is not overriden in the child class then this will get executed 
    }
 }
        class SubClass extends SuperClass { 
        public void count(){
        //If this exists, this will be executed otherwise the parent count() will be executed
        }
        }
        class Test
        {
            public static void main(String[] args)
            {
                new SubClass().count();
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM