java,属性覆盖,方法覆盖
class Rootb
{
int x = 1;
public Rootb(int i)
{
}
public int getI()
{
return x;
}
public void setI(int x)
{
this.x = x;
}
}
class Stemb extends Rootb
{
private int x = 2;
public Stemb(int i)
{
super(i);
}
public int getI()
{
return x;
}
public void setI(int x)
{
this.x = x;
}
}
public class Test
{
public static void main(String args[])
{
Rootb stb = new Stemb(47);
stb.x = 3;
System.out.println(stb.x);
System.out.println(((Stemb) stb).getI());
System.out.println(stb.getI());
System.out.println(((Stemb) stb).getI());
stb.setI(5);
System.out.println(stb.x);
System.out.println(((Stemb) stb).getI());
System.out.println(stb.getI());
System.out.println(((Stemb) stb).getI());
Stemb rootb = (Stemb) new Rootb(47);
rootb.setI(3);
System.out.println(rootb.getI());
System.out.println(((Rootb) rootb).x);
}
{
int x = 1;
public Rootb(int i)
{
}
public int getI()
{
return x;
}
public void setI(int x)
{
this.x = x;
}
}
class Stemb extends Rootb
{
private int x = 2;
public Stemb(int i)
{
super(i);
}
public int getI()
{
return x;
}
public void setI(int x)
{
this.x = x;
}
}
public class Test
{
public static void main(String args[])
{
Rootb stb = new Stemb(47);
stb.x = 3;
System.out.println(stb.x);
System.out.println(((Stemb) stb).getI());
System.out.println(stb.getI());
System.out.println(((Stemb) stb).getI());
stb.setI(5);
System.out.println(stb.x);
System.out.println(((Stemb) stb).getI());
System.out.println(stb.getI());
System.out.println(((Stemb) stb).getI());
Stemb rootb = (Stemb) new Rootb(47);
rootb.setI(3);
System.out.println(rootb.getI());
System.out.println(((Rootb) rootb).x);
}
}
3
2
2
2
3
5
5
5
Exception in thread "main" java.lang.ClassCastException: Rootb cannot be cast to Stemb
at Test.main(Test.java:59)
结论:java属性不覆盖,方法覆盖。
如果你喜欢本文, 请长按二维码,关注公众号 分布式编程.
作者:分布式编程
出处:https://zthinker.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。