Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

java - How to call a super method (ie: toString()) from outside a derived class

existantial question

if i have a class hierarchy like:

public class TestSuper {
    public static class A {
        @Override
        public String toString() { return "I am A"; }
    }
    public static class B extends A {
        @Override
        public String toString() { return "I am B"; }
    }
    public static void main(String[] args) {
        Object o = new B();
        System.out.println( o ); // --> I am B
        // ?????? // --> I am A 
    }
}    

From the main method, is it possible to call the toString of A when the instance is of type B ???

of course, something like o.super.toString() doesn't compile ...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't, and very deliberately so: it would break encapsulation.

Suppose you had a class which used a method to validate input by some business rules, and then call the superclass method. If the caller could just ignore the override, it would make the class pretty much pointless.

If you find yourself needing to do this, revisit your design.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...