zoukankan      html  css  js  c++  java
  • [java] 转型

    A为父类,子类B、C

    第20行发生向上转型,a对象调用C覆写过的print()方法

    若为A a = new B(); 则调用B覆写过的print()方法

    创建对象时使用向上转型,能够统一参数类型(23行),便于程序设计

     1 package inheritance;
     2 
     3 class A{
     4     public void print() {
     5         System.out.println("A.pirnt");
     6     }
     7 }
     8 class B extends A{
     9     public void print() {
    10         System.out.println("B.print");
    11     }
    12 }
    13 class C extends A{
    14     public void print() {
    15         System.out.println("C.print");
    16     }
    17 }
    18 public class TestDemo {
    19     public static void main(String args[]) {
    20         A a1 = new B();
    21         A a2 = new C();
    22         fun(a1);
    23         fun(a2);
    24         System.out.println(a1 instanceof A);
    25         System.out.println(a1 instanceof B);
    26         System.out.println(a1 instanceof C);
    27     }
    28 public static void fun(A a) {
    29     a.print();
    30 }
    31 }

    结果:

    B.print
    C.print
    true
    true
    false

    如果子类有自己的特殊方法,没有在父类中定义,则父类访问子类的方法需要将父类对象向下转型:B b = (B) a,但这样会破坏参数的统一性,所以在开发中不建议使用

    原则:以父类方法为主,子类可以覆写父类方法,但尽量不要扩充新方法

  • 相关阅读:
    哈尔滨理工大学软件与微电子学院第八届程序设计竞赛同步赛(低年级)
    ACM_X章求和(数学)
    goj 扫雷(dfs)
    Sereja and Brackets(括号匹配)
    NOIP模拟赛 迷路
    NOIP模拟赛three(3)
    NOIP模拟赛2(two)
    NOIP模拟赛1(one)
    czy的后宫5
    [BZOJ3436]小K的农场
  • 原文地址:https://www.cnblogs.com/cxc1357/p/11033047.html
Copyright © 2011-2022 走看看