动手动脑

一、

class Mammal{}
class Dog extends Mammal {}
class Cat extends Mammal{}

public class TestCast
{
public static void main(String args[])
{
Mammal m;
Dog d=new Dog();
Cat c=new Cat();
m=d;
//d=m;
d=(Dog)m;
//d=c;
//c=(Cat)m;

}
}

(1)子类对象中既包含父类中继承来的变量,还包括自身所特有的.当把子类对象去赋值给父类对象时,把两者共有的部分进行了赋值。

(2)反之,父类对象赋值给子类对象时,由于父类对象不能够提供子类对象所特有的变量,因此会报错.

public class TestInstanceof
{
public static void main(String[] args)
{
//声明hello时使用Object类,则hello的编译类型是Object,Object是所有类的父类
//但hello变量的实际类型是String
Object hello = "Hello";
//String是Object类的子类,所以返回true。
System.out.println("字符串是否是Object类的实例:" + (hello instanceof Object));
//返回true。
System.out.println("字符串是否是String类的实例:" + (hello instanceof String));
//返回false。
System.out.println("字符串是否是Math类的实例:" + (hello instanceof Math));
//String实现了Comparable接口,所以返回true。
System.out.println("字符串是否是Comparable接口的实例:" + (hello instanceof Comparable));
String a = "Hello";
//String类既不是Math类,也不是Math类的父类,所以下面代码编译无法通过
//System.out.println("字符串是否是Math类的实例:" + (a instanceof Math));
}
}

 

 为什么子类的构造方法在运行之前必须调用父类的构造方法?

子类继承了父类,那么就默认地含有父类的公共成员方法和公共成员变量,这些方法和变量在子类里不再重复声明。通过调用父类的构造方法来初始化父类的公共成员方法和公共成员变量,子类才可以正常使用父类方法或变量。

posted @   涨涨涨张  阅读(154)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示