一、继承中的构造函数
有了子父类之后构造函数的特点:
在对子类对象进行初始化的时候,父类的构造方法也会运行,
那是因为子类的构造函数默认第一行
有一条隐式的语句super();
子类每个构造方法第一行都有一个隐式的super();
class fu{
String name;
fu(){
System.out.println("父类构造方法");
}
fu(String n){
this.name=n;
System.out.println("父类有参构造方法");
}
}
class zi extends fu{
zi(){
System.out.println("子类构造方法");
}
zi(String n){
super("小明");
this.name="小李";
System.out.println("子类构造方法");
}
}
public class A6_49{
public static void main(String[] args){
zi z=new zi("小李");
}
}
二、对象转型
对象的转型:
1.对象的向上转型 子类转成父类 默认进行 父类引用指向子类对象
2.对象的向下转型 父类转成子类 强制进行
关键字:instanceof 测试左边的对象是否是右边的实例(对象)
如果是返回true 如果不是返回false
class Animal{
void sleep(){
System.out.println("睡觉中");
}
}
class Cat extends Animal{
void catchMouse(){
System.out.println("捕鼠");
}
}
class Dog extends Animal{
}
public class A6_23{
public static void main(String[] args){
Animal a=new Cat();//向上转型(把a当成一个Animal来看待,a不能访问catchMouse)
Cat c=(Cat)a;//向下转型(把c当成一只猫来看待了)
c.slepp();
c.catchMouse();
System.out.println(a instanceof Animal);
}
}