如题,请看下列代码中的注释部分
public class Test {
protected void display() {
System.out.println("father's display");
} Test() {
System.out.println("Test Constructor");
} static public void main(String[] args) { Test f = null;
TestSon s = new TestSon(); f = (Test) s; // 为什么强制转换不成功呢?!!! f.display(); s.display(); s = (TestSon) f; s.display(); }
}class TestSon extends Test { TestSon() {
System.out.println("TestSon Constructor");
} protected void display() {
System.out.println("son's display");
}}Test Constructor
TestSon Constructor
son's display
son's display
son's display
f = (Test) s;的写法是不是有错误?
public class Test {
protected void display() {
System.out.println("father's display");
} Test() {
System.out.println("Test Constructor");
} static public void main(String[] args) { Test f = null;
TestSon s = new TestSon(); f = (Test) s; // 为什么强制转换不成功呢?!!! f.display(); s.display(); s = (TestSon) f; s.display(); }
}class TestSon extends Test { TestSon() {
System.out.println("TestSon Constructor");
} protected void display() {
System.out.println("son's display");
}}Test Constructor
TestSon Constructor
son's display
son's display
son's display
f = (Test) s;的写法是不是有错误?
你之所以输出的都是son's display ,是因为多态的原因。
好好看下多态方面的知识吧
自己看看比大家给你讲好多了
TestSon s = new TestSon();
f = (Test) s;
其实你的这个写法和Test t=new TestSon();是一样的。这里没有必要进行强制类型的转换,不转换编译也不会出错的。这里一个子类对象的引用被赋给了一个超类的引用变量时,你只能访问超类定义的那一部份方法或变量。
而且当你new一个子类的时候会首先调用父类中的构造方法,然后再调用子类中的构造方法
但是当你的子类中出现了和父类中相同的方法和变量的时候,那么当你调用这个方法的时候都会是子类中的方法。
这就是方法的重写也就是子类中的方法覆盖了父类的,但父类中的方法也只是被隐藏了。你可以通过super来调用父类中的方法或变量。我重写了你的程序可以调用父类的方法public class Test {
protected void display() {
System.out.println("father's display");
}
Test() {
System.out.println("Test Constructor");
}
static public void main(String[] args) {
Test f = null;
TestSon s = new TestSon();
f = s; // 为什么强制转换不成功呢?!! 这里等同于Test t=new TestSon();我上面已经说明了。
f.display();
s.display();
/*s = (TestSon) f;
s.display();*/ //如果你想要调用父类中的方法,强制转换是没有用的。
s.testDisplay();
}
}class TestSon extends Test {
int i;
TestSon() {
i=3;
System.out.println("TestSon Constructor");
}
protected void display() {
System.out.println("son's display");
}
protected void testDisplay(){
super.display();
}
}
其实是否强制转换是一样的!如果你想调用父类的方法,是不能用强制转换来实现的!
new一个父类的实例就行了!
因为TestSon就是Test类型,再强制转换等同于无效
查:
(Test)s instanceof TestSon 仍为true强制转换允许在编译期将源类型当作目标类型来对待
在某些情况下要做一些相应的运行期检查
各位可不可以给我提供个对象的强制转换的例子,我知道这是多态,但是不明白如何进行数据的cut,比如将子类对象中比父类对象多出的属性去掉
[/Quote
不知道你所谓的cut是不是C++里的object slice之类的东西,java没有。
java中对象都存在堆里,都是通过引用来访问的。转换也是对引用类型的转换,对对象本身不造成影响。不想cpp,有栈里的对象