Java学习

Java继承的关系:

继承可以理解为一个对象从另一个对象获取属性的过程。

如果类A是类B的父类,而类B是类C的父类,我们也称C是A的子类,类C是从类A继承而来的。一个子类只能有一个父类

继承中最常使用的两个关键字是extends和implements。

通过使用这两个关键字,我们能实现一个对象获取另一个对象的属性。

实例:

class Animal {

     public void tell() {

        System.out.println("动物大家庭");

      }

    }

 

    class Dog extends Animal {

      void eatTest() {

        super.tell();  // super 调用父类方法

      }

    }

 

    public class Test {

      public static void main(String[] args) {

        Animal a = new Animal();

        a.tell();

        Dog d = new Dog();

        d.eatTest();

      }

    }

程序中Animal是主类,Dog是子类,Dog从Animal类处继承了tell方法,在结果中输出了父类中的内容。

final 关键字声明类可以把类定义为不能继承的,即最终类;将Dog用final修饰,当创建一个Dog的子类时:

package org.my_project;

 

class Animal {

       void tell() {

        System.out.println("动物大家庭");

      }

    }

 

    final class Dog extends Animal {

      void eatTest() {

        super.tell();  // super 调用父类方法

      }

    }

    final class One extends Dog {

          void newtell() {

            super.tell();  // super 调用父类方法

          }

        }

 

    public class Test {

      public static void main(String[] args) {

        Animal a = new Animal();

        a.tell();

        Dog d = new Dog();

        d.eatTest();

        One c=new One();

        c.newtell();

      }

    }

结果如图所示:

原文地址:https://www.cnblogs.com/zcz1995/p/11877319.html