简体   繁体   English

如何在Java中使用super?

[英]How do I use super in java?

public class A {

public void foo() {
System.out.println("A's foo");
    }
}



public class B extends A {
    public void foo() {
    System.out.print("B's foo");
    }
}



public  class Test1 {
public static void main(String[] args){
    A a= new B();
    a.foo();
  }
}

I want to use A's foo, what is the syntax for doing that? 我想使用A的foo,这样做的语法是什么? I tried a.super.foo(); 我尝试了a.super.foo(); .

Thank you 谢谢

You can only do so from within the class B . 您只能从B类内部进行操作。 You won't be able to invoke A 's foo from outside A or B classes. 您将无法从AB类外部调用Afoo

A a= new B(); will always set the reference a to an instance of B . 将始终将引用a设置为B的实例。 Thus, even though you cast it to A , at runtime the method that gets invoked is B.foo . 因此,即使将其B.fooA ,在运行时调用的方法也是B.foo That's runtime polymorphism. 那就是运行时多态。

I am really uneasy about a design that needs to do this kind of thing. 对于需要执行此类操作的设计,我真的感到不安。 If you want the object to behave like an A , why did you create a B ? 如果要让对象表现得像A ,为什么要创建B

You cannot use super from the outside of the class. 您不能从课程外部使用super Assuming you really , really need this (but I really doubt you can't find a better way) the best you can do about it is to expose a method that does this call to the outside: 假设您确实 非常需要此方法(但我真的很怀疑您找不到更好的方法),对此,您可以做的最好的事情就是将执行此调用的方法公开给外部:

public class B extends A {
    public void super_foo() {
        super.foo();
    }
    public void foo() {
        System.out.print("B's foo");
    }
}

public  class Test1 {
    public static void main(String[] args){
        A a= new B();
        a.super_foo();
    }
}

Here is it 就这个

    public class A {

    public void foo() {
    System.out.println("A's foo");
        }
    }



    public class B extends A {
        public void foo() {
        super.foo();
        System.out.print("B's foo");
        }
    }



public  class Test1 {
public static void main(String[] args){
    A a= new B();
    a.foo();
  }
}

What you want to achieve will work if the method is static. 如果该方法是静态的,那么您想要实现的目标将起作用。 Non virtual methods in java Java中的非虚拟方法

public class A {
    public static void foo() {
        System.out.println("A's foo");
    }
}

public class B extends A {
    public static void foo() {
        System.out.print("B's foo");
    }
}

public  class Test1 {
    public static void main(String[] args){
       A a= new B();
       a.foo();
    }
}

You can't access it. 您无法访问它。 The keyword is that it has been overridden by Java so it's no longer accessible. 关键字是它已被Java 覆盖 ,因此不再可访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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