JAVA class and object ------ inheritance, java ------ inheritance
Understanding: inheritance can be understood as an object's process of obtaining attributes. If Class A is the parent class of Class B, and Class B is the parent class of class C, we also say that C is A subclass of Class A, and class C is inherited from Class. In java, class inheritance is a single inheritance, that is, a subclass can only have one parent class.
Keywords: extends and implements.
The use of these two keywords determines whether an object is a IS-A (a) relationship with another object.
Example:
// A.javapublic class A { private int i; protected int j; public void func() { }} // B.javapublic class B extends A {}
Note: In the preceding example, B is inherited by A, and B is A subclass of. As A subclass, B's instance has all the member variables of A, but has no access permission to private member B, which guarantees the encapsulation of.
IS-A relationships: one object is another object category! We can determine the Mammal IS-A Animal by using the instanceof operator.
class Animal{}class Dog extends Animal{}class Cat extends Animal{}class Pig extends Animal{}public class AnimalTest{ public static void main(String args[]){ Dog dog=new Dog(); Cat cat=new Cat(); Pig pig=new Pig(); System.out.println(dog instanceof Animal); System.out.println(cat instanceof Animal); System.out.println(pig instanceof Animal); }}
Let's take a look.ImplementsHow the keyword is used to represent the IS-A relationship.
ImplementsKeywords cannot be used in this case when the class inheritance interface is used.Extends.
interface Animal{}class Mammal implements Animal{}class Dog implements Animal{}public class AnimalTestTwo { public static void main(String args[]){ Mammal m = new Mammal(); Dog d = new Dog(); System.out.println(m instanceof Animal); System.out.println(d instanceof Animal); }}
Java only supports single inheritance (inheriting basic classes and abstract classes), but we can use interfaces (implementing multiple inheritance interfaces). The script structure is as follows:
Public class Apple extends Fruit implements Fruit1, Fruit2 {}
Generally, we use the extends keyword to inherit basic classes and abstract classes, and use the implements keyword to inherit interface classes.