JAVA中方法和变量在继承中的覆盖和隐藏

参考博文:

https://www.cnblogs.com/dolphin0520/p/3803432.html 讲的是继承

https://www.cnblogs.com/it12345/p/5221673.html 讲的是覆盖和隐藏

下面是两个比较好的例子~

子类继承父类后都是先运行父类的构造方法,然后在运行子类的构造方法。列如下:

public class Test {
    public static void main(String[] args)  {
        new Circle();
    }
}
 
class Draw {
     
    public Draw(String type) {
        System.out.println(type+" draw constructor");
    }
}
 
class Shape {
    private Draw draw = new Draw("shape");
     
    public Shape(){
        System.out.println("shape constructor");
    }
}
 
class Circle extends Shape {
    private Draw draw = new Draw("circle");
    public Circle() {
        System.out.println("circle constructor");
    }
}

输出结果:

shape draw constructor
shape constructor
circle draw constructor
circle constructor

但是在java继承里有覆盖和隐藏的问题:例如下面:

public class Test {
    public static void main(String[] args)  {
        Shape shape = new Circle();
        System.out.println(shape.name);
        shape.printType();
        shape.printName();
    }
}
 
class Shape {
    public String name = "shape";
     
    public Shape(){
        System.out.println("shape constructor");
    }
     
    public void printType() {
        System.out.println("this is shape");
    }
     
    public static void printName() {
        System.out.println("shape");
    }
}
 
class Circle extends Shape {
    public String name = "circle";
     
    public Circle() {
        System.out.println("circle constructor");
    }
     
    public void printType() {
        System.out.println("this is circle");
    }
     
    public static void printName() {
        System.out.println("circle");
    }
}

输出结果是:

shape constructor
circle constructor
shape
this is circle
shape

我猜在运行:shape.printType()的时候你一定会认为运行的结果是thie is shape

但是这里由于继承存在隐藏和覆盖的问题:

覆盖只针对非静态方法

隐藏是针对成员变量和静态方法

由于printType()不是成员变量也不是静态方法所以他就被父类覆盖了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值