Java A b = new B(); B继承A .

君Q子2022-10-04 11:39:541条回答

Java A b = new B(); B继承A .
定义类A 和类B 如下:
class A {
int a=1;
double d=2.0;
void show(){
System.out.println("Class A: a="+a +"td="+d);
}
}
class B extends A{
float a=3.0f;
String d="Java program.";
void show(){
super.show( );
System.out.println("Class B: a="+a +"td="+d);
}
}
(1) 若在应用程序的main 方法中有以下语句:
A a=new A();
a.show();
则输出的结果如何?
(2) 若在应用程序的main 方法中定义类B 的对象b :
A b=new B();
b.show();
则输出的结果如何?

(我知道答案,只是求详解,第二小问的详细解释,初学不懂,求教!)

已提交,审核后显示!提交回复

共1条回复
老鼠嘟嘟 共回答了13个问题 | 采纳率84.6%
A b=new B():
因为B类是A类的子类,所以上面语句发生了向上转型. new B()会在堆内存中产生一个B类的实例,
A b会在栈内存中产生一个A类的引用.
A b = new B()会让b指向堆内存中的new B()实例,但是该实例时B类的实例,这是就会发生向上转型.
如果子类中存在和父类相同名称和参数的方法,这种情况叫做多态性,子类覆写父类方法,
发生向上转型后,调用这种被子类覆写过的方法,那么会直接调用类B的方法show().
1年前

相关推荐

英语作文:我们是否继承传统节日?
windbut1年前1
牛鼻子老道123 共回答了16个问题 | 采纳率93.8%
您好:The Prevalence of Western Holidays
It is noticeable that western holidays are becoming increasingly popular day by day, while Chinese traditional holidays are being somewhat neglected. Old people often complain that Chinese New Year has lost its real meaning. To their astonishment, young people in China, ignorant about Chinese traditional holidays, are crazy about Christmas or Valentine's Day.
There are several possible reasons for this phenomenon. First, western nations, such as the United States and Britain, are powerful and dominant in every aspect. Everything in these countries is assumed to be superior and adored by some modern young people. Second, the prevalence of English as a world language and the development of globalization enable western culture to flood in China. Overwhelmed by such a trend, Chinese unconsciously get involved in western culture. Last but not least, some Chinese people have blind faith in foreign things while dismiss our own possessions with contempt.
I am critical of this trend. China boasts a brilliant history and splendid traditions. In modern times, Chinese tradition should be preserved and promoted. But it seems that young people no longer treasure the tradition. On the contrary, they turn to pursue enthusiastically a supposedly more modern culture. If this trend is allowed to continue, the priceless heritage of our ancestors will be replaced by western traditions. Nobody expects such a consequence. So let's join hand in hand to protect Chinese tradition!
希望对您的学习有帮助
【满意请采纳】O(∩_∩)O谢谢
欢迎追问O(∩_∩)O~
祝学习进步~
Animal a=new Animal (); Cat c=new Cat(); Cat继承 Animal a inst
Animal a=new Animal (); Cat c=new Cat(); Cat继承 Animal a instanceof Cat为什么不可以?
书上这句话“基类的引用类型变量可以指向其子类的对象”不是这么解释的吗?
我的意思是 Animal a=new Animal (); Cat c=new Cat(); Cat继承了 Animal,成为它的子类,先给出的条件就这些,然后书上说a instanceof Cat 语句合法,c instanceof Animal就不和法,好像根据就是这句话 “基类的引用类型变量可以指向其子类的对象”
,我不太明白,书上还有其他的3句话也不理解
1一个基类的引用不可以访问其子类对象新增加的成员(属性和方法).
2可以使用引用变量instanceof类名来判断引用变量所指向的对象是否属于该类或该类的子类.
3子类的对象可以当做基类的对象来使用称作向上型,反之为向下型.
flyingsun20051年前1
19791125 共回答了14个问题 | 采纳率100%
看来没人能说明白