子类父类拥有同名的方法时……

本文探讨了在Java编程中,当子类和父类拥有同名方法时,如何确定调用哪个方法,这涉及到面向对象的多态特性。同时,还解释了字段隐藏现象,即子类中的字段会隐藏父类同名字段,以及如何通过super关键字访问父类字段。文章通过多个代码示例进一步阐明这些概念。
摘要由CSDN通过智能技术生成

子类父类拥有同名的方法时……

(这个程序是不能运行的

 

 

package yanzheng;

public class ParentChildTest {

public static void main(String[] args) {

Parent parent=new Parent();

parent.printValue();

Child child=new Child();

child.printValue();

parent=child;

parent.printValue();

parent.myValue++;

parent.printValue();

((Child)parent).myValue++;

parent.printValue();

}

}

 

class Parent{

public int myValue=100;

public void printValue() {

System.out.println("Parent.printValue(),myValue="+myValue);

}

}

class Child extends Parent{

public int myValue=200;

public void printValue() {

System.out.println("Child.printValue(),myValue="+myValue);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值