重写 final关键字 多态调用子类特有的属性及行为(向上向下转型)

1.override 重写:在继承中,子类与父类方法名相同,参数列表相同,的方法叫重写,与返回值有关;  主要应用于系统升级.

2.final 关键字:

  可修饰:1.类-->被修饰后该类不能被继承

       2.方法 -->被修饰后该方法不能被重写

    3.变量-->被修饰后该变量为常量,只能赋值一次, 常量标识符全部用大写

3.多态:事物的多种形态

  满足条件:

  1.继承

  2.重写

  3.父类引用指向子类对象;

  多态弊端:不能调用子类特有的属性和行为.

  向上转型:用父类名

  向下转型:类名  对象名 =  (类名) 多态引用对象名

例:新建Animal 为父类   cat和Dog为子类 通过向下转型使用子类特有的属性及行为 test为主函数代码

public class Animal {
    public String name = "动物";
    public void eat(){
        System.out.println("动物吃饭");
        
    }
    public void sleep(){
        System.out.println("动物睡觉");
    }
}

父类代码

public class cat extends Animal {
    public String name = "猫猫";
    public void eat(){
        System.out.println("猫在吃饭");
    }
    public void sleep(){
        System.out.println("猫在睡觉");
    }
    public void catchMouse(){
        System.out.println("猫在抓老鼠");
    }
}

子类cat代码

public class Dog extends Animal {
    public String name = "狗";
    public void eat(){
        System.out.println("狗在吃饭");
        
    }
    public void sleep(){
        System.out.println("狗在睡觉");
    }
    public void lookHome(){
        System.out.println("狗在看家");
    }
}

子类Dog代码

public class test {
        public static void main(String[] a){
            Animal cat = new cat();//多态    方法编译时看左边类  运行时看右边对象类
            cat.eat();
            System.out.println(cat.name);//多态 属性编译时看左边  运行时看左边
                                       //即产生弊端,不能够访问子类特有的属性和行为 需向下转型
            test te = new test();
            te.Demo(cat);
        }    
        public void Demo(Animal c){ //参数类型采用父类 可以采用父类的属性及行为 及向上转型
            System.out.println(c.name);
            if(c instanceof cat){  //通过类型匹配进行判断   如果Demo传入的实参为cat,则执行cat向下转型否则执行Dog向下转型
                cat ca = (cat)c; //向下转型语句
                System.out.println(ca.name);//向下转型后可以使用cat特有的属性
                ca.catchMouse();//向下转型后可以使用cat特有的方法(行为).
            }else if(c instanceof Dog){//同上
                Dog dog = (Dog)c;
                dog.lookHome();
            }
        }
}

运行结果为:

猫在吃饭
动物
动物
猫猫
猫在抓老鼠

主函数进行向上向下转型代码及注释,多多练习!

猜你喜欢

转载自www.cnblogs.com/lboy1205/p/9268635.html