抽象类使用自己的抽象方法

时间:2018-06-13 09:28:30

标签: java abstract-class

我最近开始阅读关于Abstract类的内容。我访问过的大部分网站都看到父类是抽象的,而子类定义了父类的抽象方法。对我来说很好,但最近我看到了使用抽象类的不同方式。代码正在运行,但我无法理解逻辑。代码如下所示


    abstract class TestParent
    {
      abstract void display();

       public void accessdisplay()
       {
         display();
       }
    }    //  TestParent

    public class TestChild extends TestParent
    {
       void display()
       {
          System.out.println("child define display");
       }

       void print()
       {
          System.out.println("This is print");
       }

       public static void main(String... arg)
       {
          TestChild t_child=new TestChild();

          t_child.accessdisplay();  
          t_child.print();
          System.out.println("\n******************************************\n");

          TestParent t_parent= new TestChild();

          t_parent.accessdisplay();  
          t_parent.display();  
          //t_parent.print();
       }    
    }


代码工作....但我从未看到抽象类尝试使用自己的抽象方法....

代码“t_parent.accessdisplay()”如何工作?我知道TestChild被引用到TestParent ....所以TestChild可以访问父类方法....但是display()是一个抽象方法..在子类中定义...对象如何“t_parent”这是对父类的引用,可以访问子类中定义的方法

或者我想知道关于抽象类的任何内容......我在哪里缺失

请帮帮我

1 个答案:

答案 0 :(得分:0)

这是因为称为“ 多态性”的OO概念。

“ t_chiled”和“ t_parent”是对象引用变量。 它们本身不是对象。可以将它们视为遥控器(电视遥控器)。每种方法都映射到遥控器中的按钮。随着子类从父类继承方法,子对象可以响应父遥控器中的所有按钮。 因此,可以在需要父对象的位置替换子对象。

在此代码中

TestParent t_parent= new TestChild();

父对象引用变量(t_parent)引用在堆上创建的TestChild对象。它不引用TestParent对象。因此,它在以下情况下没有引用抽象方法

t_parent.accessdisplay();

发生这种情况。它只是引用TestChild对象内部的重写方法。

有关Java多态性的更多信息,请访问https://www.tutorialspoint.com/java/java_polymorphism.htm