简体   繁体   中英

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? I tried a.super.foo(); .

Thank you

You can only do so from within the class B . You won't be able to invoke A 's foo from outside A or B classes.

A a= new B(); will always set the reference a to an instance of B . Thus, even though you cast it to A , at runtime the method that gets invoked is 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 ?

You cannot use super from the outside of the class. 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

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.

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