java重写和上转型对象

public class Test {
    
    
    public static void main(String[] args) {
    
    
        B b =new B();
        System.out.println(b.f(10.0,8.0)); //调用重写方法,98.0
        System.out.println(b.g(3));  //调用重写方法,12
        A a  = new B();  //a是上转型对象
        System.out.println(a.f(10.0,8.0));  //调用子类重写后的实例方法,98.0,a是对象B构造的地址空间
        System.out.println(a.g(3));  //调用被隐藏的静态方法,9
    }
}
class A {
    
    
    double f(double x,double y){
    
      //实例方法
        return x+y;
    }
    static int g(int n){
    
      //静态方法或类方法
        return n*n;
    }
}
class B extends A{
    
        //B继承A
    double f(double x,double y){
    
       //重写,隐藏继承方法
        double m = super.f(x,y);
        return m+x*y;
    }
    static int g(int n){
    
    
        int m =A.g(n);
        return m+n;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_45142629/article/details/118189691