Accessing super class function using subclass object

前端 未结 5 1442
庸人自扰
庸人自扰 2021-01-18 22:08

I have an object of a subclass extending its superclass. There is an overridden method in subclass which can be called using the object. Is that possible to call the superc

相关标签:
5条回答
  • 2021-01-18 22:46

    Here it prints Subclass go . Instead I have to print Superclass go

    Alright, then do not override go method @ subclass, it will call superclass implementation.

    If you want to run super implementation, and have some other additional code @ subclass, you call super.go(); and then run some other statements.

    It's ok, as you are reusing already written code, you shouldn't copy-paste code from superclass and put it into subs as it's code duplication. But if your goal is to change behaviour completely, then don't call super

    0 讨论(0)
  • 2021-01-18 22:49

    Instead of:

    System.out.println("Subclass go");
    

    Write

    super.go();
    

    (Or, you know, just don't implement that method ...).

    0 讨论(0)
  • 2021-01-18 22:53

    Is there any way to achieve this? No, there isn't.

    At runtime the JVM will pick the methods to call based on the instance type (that's polymorphism for you), not based on the type it is declared with.

    Your instance is a subclass instance, so the go() method in the subclass will be called.

    0 讨论(0)
  • 2021-01-18 23:05

    One way would be to make the subclass call teh super classes implementation. But I'm assuming thats not what you want?

    class SubClass extends SomeClass {    
    SubClass() {}    
        @Override    
        public void go() {    
            super.go
        }
    }
    
    0 讨论(0)
  • 2021-01-18 23:06

    No, it's not possible, and if you think you need it, rethink your design. The whole point of overriding a method is to replace its functionality. If a different class knows that much about that class's internal workings, you're completely killing encapsulation.

    0 讨论(0)
提交回复
热议问题