java向上继承

这篇博客探讨了一个简单的Java代码示例,展示了在继承结构中构造器的调用顺序以及静态方法的行为。作者发现当创建子类对象时,会先执行父类和子类的构造器,然后输出父类的属性和子类的方法。然而,最后一个输出是静态方法`printName()`,由于静态方法不会被覆盖,因此输出的是父类的`shape`,而非预期的`circle`。通过这个小例子,作者提醒读者注意静态方法在继承中的行为。
摘要由CSDN通过智能技术生成
晚上刚看了一个人的博客代码,

public class day01_1 {
    public static void main(String[] args) {
        Shape sh = new circle();
        System.out.println(sh.name);
        sh.printType();
        sh.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");
    }
}

(出自「yanghan1222」的原创文章, 链接https://blog.csdn.net/yanghan1222/article/details/8015453)

 结果的输出与我想象的并不一样:

shape constructor
circle constructor
shape
this is circle
shape

首先是创建对象时先运行两个构造器,然后是正常输出父类属性,子类方法,但最后一个我并不理解,为什么不是circle?
钻研了20分钟之后我才发现:静态方法不能被覆盖hhh

虽然是相当简单的一道题,但终归是由收获

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值