java,屬性覆蓋,方法覆蓋
阿新 • • 發佈:2019-02-16
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屬性不覆蓋,方法覆蓋。