继承,多态的再学习

继承,多态的再学习

继承

本人,小菜一枚。一直在学习java,对于java中继承,多态一直以来不太了解。对继承多态,一直处于一种半知半解的状态,今天又特意看了一下,决定写下这篇文章。

从字面意思理解就是儿子继承了他爸的东西,这样儿子就有了他爸的东西。
再深入一点理解,就是儿子对于继承的他爸的东西不太满意,毕竟是老一代的嘛 东西过时了对吧,需要与时俱进,就稍加改进改进。OK,代码实现一下

//父类
public class Father{
    public void hello(){
        System.out.println("this is 老子");
    }
}
//子类
public class Son extends Father {
    public void hello(){
        System.out.println("this is 小子");
    }
}
//测试类
public class Test {
    public static void main(String[] args) {
        Father father = new Son();
        Son son = new Son();
        father.hello();
        son.hello();
    }
}

看一下运行结果:

this is 小子
this is 小子

这儿子太不孝顺了,竟然不让调用他老子的。今个非教训他一顿,来个强制转换,

public class Test {
    public static void main(String[] args) {
        Father father = new Son();
        Son son = new Son();
        father.hello();
        son.hello();
        //强制转换
        Father f = (Father)father;
        f.hello();
    }
}

再来看一下运行结果:

this is 小子
this is 小子
this is 小子

这……,或许是他老子的确实跟不上时代了。

总结

上例中,我们实例化了两个Son对象,分别以Father和Son类型来引用它。father.hello()表面上是调用了father类型的方法,但是它实际上是一个虚拟方法。以Father类型引用的变量father调用say方法时,实际上并不是调用Father类中的hello方法,而是Son类中的hello方法。该行为被称为虚拟方法调用。 –这段话引用自(作为一枚小菜,表达能力还有待提高):

http://lib.csdn.net/article/javase/49970

如果子类中没有重写父类中的方法,那么我们也可以使用father.hello()来调用父类中的hello方法,还可以用father来调用父类中未被重写的方法。

多态

多态是同一个行为具有多个不同表现形式或形态的能力。就比如跑这个动作,如果是人的话就是用两条腿跑,如果是猫的话就是四条腿。那跑这个动作就具有多态性。OK,代码实现一下

public interface Run {
void run();
}

//人
public class Human implements Run {
    public void run() {
        System.out.println("人类,两条腿跑");
    }
}

//猫
public class Cat implements Run {
    public void run() {
        System.out.println("猫,四条腿跑");
    }
}

//测试类
public class Test {
    public static void main(String[] args) {
        Run cat = new Cat();
        Run human = new Human();
        cat.run();
        human.run();
    }
}

运行结果如下:

 猫,四条腿跑
 人类,两条腿跑

上面的测试类中,使用的是Run类的引用,但却是实例化的Cat,Human类的对象,所以就调用了对应的对象的方法。刚才,在Run接口中写了一个default方法(JDK8中允许在接口中实现方法,但是要用default修饰),用cat也可以调用。

多态不仅可以通过接口来体现,还可以通过继承来体现,多个子类对同一方法的重写可以表现出不同的行为。也是多态的体现。

突然想起来了转型,既然子类对象的引用可以调用父类的方法,为什么还要转型呢?那就写到这吧,继续学习去…….

最后: 由于这是本菜的第一篇文章,难免有用词不当的地方,而且作为一名小菜,有些术语用的可能不正确。如果有错误的地方还请各位大神不吝赐教。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章