[Java] Java Advanced Study Notes (2) - Object-Oriented (Inheritance)

1. The concept of inheritance

Inheritance is a cornerstone of Java object-oriented programming techniques because it allows the creation of hierarchical hierarchies of classes.

Inheritance means that the subclass inherits the characteristics and behaviors of the parent class, so that the subclass object (instance) has the instance fields and methods of the parent class, or the subclass inherits the methods from the parent class, so that the subclass has the same behavior as the parent class.

Inheritance in life:

insert image description here
Rabbits and sheep are herbivores, and lions and leopards are carnivores.
Herbivores and carnivores are again animals.

So the relationship that inheritance needs to conform to is: is-a, the parent class is more general, and the subclass is more specific .

Although both herbivores and carnivores belong to animals, their attributes and behaviors are different, so subclasses will have the general characteristics of the parent class and also have their own characteristics.

Format:

class 父类 {
    
    
}

子类 extends 父类 {
    
    
    
}

Inherited Features

  • Inheritance is a relationship from subclass to parent class;

  • The subclass inherits a parent class, **the subclass can directly get the attributes (member variables) and behaviors (methods) of the parent class**;

  • Inheritance in java is an "is a" relationship. Lion extends Animal : Lion is an animal;

  • In java, subclasses are more powerful. Subclasses not only inherit the functions of the parent class, but also define their own functions.

  • The subclass inherits the parent class, and the subclass gets the properties and behaviors of the parent class, but not all the properties and behaviors of the parent class can be inherited by subclasses.

  • Subclasses cannot inherit constructors from parent classes : subclasses have their own constructors (no controversy)

Second, the influence of constructors in inheritance

If the parent class constructor has no parameters, there is no need to use the super keyword to call the parent class constructor in the subclass constructor, and the system will automatically call the parent class no-argument constructor.


class SuperClass {
    
    
  private int n;
  SuperClass(){
    
    
    System.out.println("SuperClass()");
  }
  SuperClass(int n) {
    
    
    System.out.println("SuperClass(int n)");
    this.n = n;
  }
}
// SubClass 类继承
class SubClass extends SuperClass{
    
    
  private int n;
  
  SubClass(){
    
     // 自动调用父类的无参数构造器
    System.out.println("SubClass");
  }  
  
  public SubClass(int n){
    
     
    super(300);  // 调用父类中带有参数的构造器
    System.out.println("SubClass(int n):"+n);
    this.n = n;
  }
}
// SubClass2 类继承
class SubClass2 extends SuperClass{
    
    
  private int n;
  
  SubClass2(){
    
    
    super(300);  // 调用父类中带有参数的构造器
    System.out.println("SubClass2");
  }  
  
  public SubClass2(int n){
    
     // 自动调用父类的无参数构造器
    System.out.println("SubClass2(int n):"+n);
    this.n = n;
  }
}
public class TestSuperSub{
    
    
  public static void main (String args[]){
    
    
    System.out.println("------SubClass 类继承------");
    SubClass sc1 = new SubClass();
    SubClass sc2 = new SubClass(100); 
    System.out.println("------SubClass2 类继承------");
    SubClass2 sc3 = new SubClass2();
    SubClass2 sc4 = new SubClass2(200); 
  }
}

The output is:

------SubClass 类继承------
SuperClass()
SubClass
SuperClass(int n)
SubClass(int n):100
------SubClass2 类继承------
SuperClass(int n)
SubClass2
SuperClass()
SubClass2(int n):200

Constructor traits after inheritance

The subclass inherits the parent class, and all constructors of the subclass will first access the no-argument constructor of the parent class by default, and then execute the constructor of the subclass itself.

为什么子类的构造器会先调用父类的构造器?

答:1. 子类的构造器的第一行默认有一个super()调用父类的无参构造器,写不写都存在

​ 2.当我们调用子类构造器初始化子类对象数据的时候,必须先调用父类构造器初始化继承自父类的属性和行为(先有爸爸,后有儿子)

3. Inherited member variables and methods

1. Access characteristics of member variables after inheritance

Proximity principle: If there is a subclass, find the subclass, if the subclass does not find the parent class, if the parent class does not exist, report an error!
thisRepresents the reference of the current object and can be used to access the member variables of the current subclass object
superRepresents the reference of the parent class object and can be used to access the member variables of the parent class

public class TestDemo {
    
    
    public static void main(String[] args) {
    
    
        Cat cat = new Cat();
        cat.show();
    }

}
class Animal{
    
    
    public String name = "动物名称";
}

class Cat extends  Animal {
    
    
    public String name = "子类名称";
    public void show() {
    
    
        String name = "局部名称";
        System.out.println(name);  //局部名称
        System.out.println(this.name);  //子类名称
        System.out.println(super.name); //父类名称
    }
}

Access characteristics of member methods after inheritance: subclass objects have priority to use existing methods of subclasses .

2. Method rewriting after inheritance (override)

Java recommends adding an @override annotation to the overridden method.
Once the @override annotation is added to the method, it must be a method that successfully overrides the parent class, otherwise an error will be reported!

Specification for method overriding :

  1. The name and parameter list of the overridden method of the subclass must be the same as the overridden method of the parent class.
  2. The return value type declaration of the subclass overridden method is either the same as the parent method, or has a smaller range than the return value type of the parent class method.
  3. The modifier permission of the overridden method of the subclass should be the same as or larger than the modifier permission of the overridden method of the parent class.
  4. The exception thrown by the overridden method declaration of the subclass should be the same as or smaller in scope than the exception thrown by the overridden method declaration of the parent class.
class Animal{
    
    
   public void move(){
    
    
      System.out.println("动物可以移动");
   }
}
 
class Dog extends Animal{
    
    
   public void move(){
    
    
      System.out.println("狗可以跑和走");
   }
}
 
public class TestDog{
    
    
   public static void main(String args[]){
    
    
      Animal a = new Animal(); // Animal 对象
      Animal b = new Dog(); // Dog 对象
 
      a.move();// 执行 Animal 类的方法
 
      b.move();//执行 Dog 类的方法
   }
}

The result of compiling and running the above example is as follows:

动物可以移动
狗可以跑和走

Summary and Expansion

summary:

  1. Method rewriting is a subclass rewriting a method that is the same as the parent class declaration to override the method of the parent class;
  2. Method rewriting needs to be annotated with @override;
  3. The core requirements of method rewriting: the method name and parameter list must be consistent with the rewritten method!

extension:

静态方法和私有方法是否可以被重写?

Answer: Neither static methods nor private methods can be overridden, and @override will report an error .

3. this and super

this代表了当前对象的引用(继承中指代子类对象)
    this.子类成员变量
    this.子类成员方法
    this(....):可以根据参数匹配访问本类中其他构造器
super代表了父类对象的引用(继承中指代了父类对象空间)
    super.父类成员变量
    super.父类的成员方法
    super(....):可以根据参数匹配访问父类的构造器

Notice:

this(...) borrows other constructors of this class; super(...) calls the constructor of the parent class. this(…) and super(…) must be placed in the first line of the constructor, otherwise an error will be reported , this(…) and super(…) cannot appear in the constructor at the same time ! !

When you need to call the overridden method of the parent class in the subclass, use the super keyword.


class Animal{
    
    
   public void move(){
    
    
      System.out.println("动物可以移动");
   }
}
 
class Dog extends Animal{
    
    
   public void move(){
    
    
      super.move(); // 应用super类的方法
      System.out.println("狗可以跑和走");
   }
}
 
public class TestDog{
    
    
   public static void main(String args[]){
    
    
 
      Animal b = new Dog(); // Dog 对象
      b.move(); //执行 Dog类的方法
 
   }
}

The result of compiling and running the above example is as follows:

动物可以移动
狗可以跑和走

4. Overload

Overloading (overloading) is in a class, the method name is the same, but the parameters are different. The return types can be the same or different.

Each overloaded method (or constructor) must have a unique list of parameter types.

The most commonly used place is constructor overloading.

Overload rules:

被重载的方法必须改变参数列表(参数个数或类型不一样);
被重载的方法可以改变返回类型;
被重载的方法可以改变访问修饰符;
被重载的方法可以声明新的或更广的检查异常;
方法能够在同一个类中或者在一个子类中被重载。
无法以返回值类型作为重载函数的区分标准。

public class Overloading {
    
    
    public int test(){
    
    
        System.out.println("test1");
        return 1;
    }
 
    public void test(int a){
    
    
        System.out.println("test2");
    }   
 
    //以下两个参数类型顺序不同
    public String test(int a,String s){
    
    
        System.out.println("test3");
        return "returntest3";
    }   
 
    public String test(String s,int a){
    
    
        System.out.println("test4");
        return "returntest4";
    }   
 
    public static void main(String[] args){
    
    
        Overloading o = new Overloading();
        System.out.println(o.test());
        o.test(1);
        System.out.println(o.test(1,"test3"));
        System.out.println(o.test("test4",1));
    }
}
  • Difference Between Overriding and Overloading

insert image description here

Fourth, single inheritance and multi-level inheritance

单继承: 一个类只能继承一个直接父类
多层继承:一个类可以间接继承多个父类(C继承B,B继承A)
一个类可以有多个子类(C继承B,D也继承B,B就有了C,D两个子类)
一个类要么默认继承了Object类,要么间接继承了Object类,Object类是Java中的祖宗类

Five, the interview test

2.1 Questions and Answers for Eight Access Forms

实例方法是否可以直接访问实例成员变量?

答:可以的,因为它们都属于对象

实例方法是否可以直接访问静态成员变量?

答:可以的,静态成员变量可以被共享访问

实例方法是否可以直接访问实例方法?

答:可以的,实例方法和实例方法都属于对象

实例方法是否可以直接访问静态方法?

答:可以的,静态方法可以被共享访问

静态方法是否可以直接访问实例变量?

答:不可以,静态方法属于类,实例变量属于对象,实例变量必须用对象访问

静态方法是否可以直接访问静态变量?

答:可以的,静态成员变量可以被共享访问

静态方法是否可以直接访问实例方法?

答:不可以,实例方法必须被对象访问

静态方法是否可以直接访问静态方法?

答:可以的,静态方法可以被共享访问

2.2 Inheritance

子类中不能继承父类东西是什么?

答:子类不能继承父类的构造器,子类有自己的构造器

子类是否可以继承父类的私有成员(私有成员变量,私有成员方法)?

答:有争议,我认为子类是可以继承父类的私有成员的,只是不能直接访问而已

子类上是否可以继承父类的静态成员?

答:子类可以继承父类的静态成员。

2.3 Rewriting

静态方法和私有方法是否可以被重写?

答:不可以,加上@Override会报错

2.4 Constructor Features After Inheritance

为什么子类的构造器会调用父类的构造器

答:子类的构造器第一行默认有super()调用父类的无参构造器,写不写都存在

2.5 Single Inheritance

为什么Java是单继承的?

Answer: Evidence by contradiction

// 假如Java可以多继承,请看如下代码
class A{
    
    
    // 成员方法
    public void test(){
    
    
        System.out.println("A");
    }
}

class B{
    
    
    // 成员方法
    public void test(){
    
    
        System.out.println("B");
    }
}
class C extends  A,B{
    
    
    public static void main(String[] args){
    
    
        C c = new C();
        c.test(); //出现了类的二义性!所以Java不能多继承!!
    }
}

Guess you like

Origin blog.csdn.net/weixin_43848614/article/details/128769355