A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 熊永标 中级黑马   /  2012-12-26 17:03  /  1811 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. class Father
  2. {
  3. }
  4. 05.class child extends Father
  5. {
  6. }
  7. 08.class Client
  8. {
  9. Father f=new Child();
  10. Chile c=(Child)f;
  11. }
复制代码
问题1:会不会丢失C的数据呢?。因为我知道把一个int类型的数据强转为byte时,数据会丢失。对于对象的强转化,实质是什么发生了变化呢?
问题2:当new 子类Child时,会在堆中创建Father对像吗?

评分

参与人数 1技术分 +1 收起 理由
邵天强 + 1

查看全部评分

4 个回复

倒序浏览
  1,  会不会丢失,这要看你的int类型的数据是多大,有没有超出byte的范围,超出就溢出了。
2, 不会创建, 只是在栈内存创建了Father的引用,用这个用指向子类对象
    1,代码体现
public class Test {

        public static void main(String[] args) {
                int a = 200;
                int b = 10;
                System.out.println((byte)a);
                System.out.println((byte)b);
        }

}

评分

参与人数 1技术分 +1 收起 理由
邵天强 + 1

查看全部评分

回复 使用道具 举报
梁俊 黑马帝 2012-12-29 15:42:26
藤椅
问题2:当new 子类Child时,会在堆中创建Father对像吗?
Father f=new Child();
会在栈中创建一个Father类型引用,在堆中创建Child类型对象,然后引用 f指向Child类型的对象
回复 使用道具 举报
梁俊 黑马帝 2012-12-29 15:47:10
板凳
  1. class Father
  2. {
  3. }
  4. class child extends Father
  5. {
  6. public void aa(){}
  7. }
  8. class Client
  9. {
  10.         Father f=new Child();
  11.         Chile c=(Child)f;
  12. }
复制代码
问题1:会不会丢失C的数据呢?。因为我知道把一个int类型的数据强转为byte时,数据会丢失。对于对象的强转化,实质是什么发生了变化呢?

f不能使用aa()方法,因为引用的类型是Father,不知道这个算不算是所谓的数据丢失
但被强转后的c可以调用aa()方法了,应该是没有数据丢失吧
回复 使用道具 举报
这里涉及到了JAVA的一个核心概念,即多态,Child继承Father,说明Child是Father的一个子类,但Father不止一个Child.下面是一个多态的完整例子。
class Father {
        public void name() {
                System.out.println("father name");
        }
}

class Child1 extends Father {
        public void name() {
                System.out.println("child1 name");
        }
}

class Child2  extends Father {
        public void name() {
                System.out.println("child2 name");
        }
}

public class Outer{
        public static void main(String[] args) {
                Father f = new Child1();
                f.name();
                Father f1 = new Child2();
                f1.name();
        }
}
//多态的实现
//1,有继承
//2,有重写
//3,父类引用指向子类对象
希望对你有帮助,
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马