The second of the three major features of Java - inheritance (essential skills for work, interviews, and learning)

Table of contents

Overview of inheritance

 Characteristics of inheritance

 Member variables in inheritance

 Member methods in inheritance

 Method overriding

Constructor method in inheritance

 super keyword 

The difference between super and this

Overview of inheritance

  • When the same attributes (member variables) and behaviors (methods) exist in multiple classes, extract these contents into a single class, then the multiple classes do not need to define these attributes and behaviors, they only need to inherit that class.
  • Subclasses can directly access non-private properties and behaviors in the parent class.
  • Use the extends keyword to create an inheritance relationship between classes.

        –class SubDemo extends Demo{} SubDemo is a subclass and Demo is a parent class

package com.demo01;
/*
 * 继承:多个类有共同的成员变量和成员方法,抽取到另外一个类中(父类),在让多个类去继承这个父类,我们的多个类就可以获取到父类中的成员了。
 * extends
 * 
 */
public class ExtendsDemo {
	public static void main(String[] args) {
		DotA d = new DotA();
		d.start();
		
		LOL l = new LOL();
		l.start();
	}
}
// 父类
class Game {
	String name;
	double version;//版本号
	String agent;//代理商
	
	//法
	public void start() {
		System.out.println("游戏启动了");
	}
	
	public void stop() {
		System.out.println("游戏关闭了");
	}
}

//子类 继承了游戏所有的属性和方法
class DotA extends Game {

}

//子类 继承了游戏所有的属性和方法
class LOL extends Game {

}

Code analysis:We create a game parent class - class game. We create DotA and LOL subclasses to inherit the game's parent class and inherit all the game's attributes and Method, we create two subclass objects and execute things in the parent class.

The results show that:

 InheritedCharacteristics

  • Java only supports single inheritance and does not support multiple inheritance.

        –A class can only have one parent class, and cannot have multiple parent classes.

        –class SubDemo extends Demo{} //ok

        –class SubDemo extends Demo1,Demo2...//This is wrong

  • Java supports multi-level inheritance (inheritance system)

        –class A{}

        –class B extends A{}

        –class C extends B{}

        Declaring a parent class: A, subclass B can inherit C, subclass C can also inherit subclass B, that is to say, a class can be both a subclass and a parent class.

package com.demo02;
/*
 * Java中继承的特点:
 * 			Java语言只支持单一继承,只能继承一个父类(一个儿子只能有一个亲爹)
 * 			Java语言支持多层继承(一个儿子可以有一个亲爹,还可以有一个亲爷爷)
 * 
 */
public class ExtendsDemo2 {
	public static void main(String[] args) {
		LOL l = new LOL();
		MobileGame s = new MobileGame();
		l.update();
		l.start();
		s.update();
		s.start();
	}
}

class Game {
	public void start() {
		System.out.println("游戏启动了");
	}
}

class PCGame extends Game {
	public void update() {
		System.out.println("PCGame更新了");
	}
}

class MobileGame extends Game {
	public void update() {
		System.out.println("MobileGame更新了");
	}
}

class LOL extends PCGame {
	
}

Code analysis:We created a parent class for Game, in which the subclasses PCGame and MobileGame both inherited the parent class Game - as the grandpa level, and LOL inherited PCGame——As the father class, we create a new LOL object.

The results show that:

 Member variables in inheritance

  • If a non-private member variable with the same name appears in the child parent class,If the subclass wants to access the variables in this class, use this; Use super to access the variable with the same name in the parent class.
  • The use of super is almost the same as the use of this.
  • this represents a reference to an object of this class; super is a reference to the parent class of the current subclass object.

Characteristics of member variables in inheritance:

Subclasses can only obtain non-private members of the parent class

If the names of member variables in the child and parent classes are different, directly obtain the member variables of the parent class.

The names of the member variables in the child and parent classes are the same, and what is obtained is the member variable of the subclass.

package com.demo02;
/*
 * 继承中成员变量的特点
 * 		子类只能获取父类非私有成员
 * 		子父类中成员变量的名字不一样,直接获取父类的成员变量
 * 		子父类中成员变量名字是一样的,获取的是子类的成员变量
 * 
 * 就近原则:谁离我近我就用谁
 * 		如果有局部变量就使用局部变量
 * 		如果没有局部变量,有子类的成员变量就使用子类的成员变量
 * 		如果没有局部变量和子类的成员变量,有父类的成员变量就使用父类的成员变量
 * 		啥都没有,出错了!!!
 * 
 * super:可以获取父类的成员变量和成员方法,用法和this是相似的
 */
public class ExtendsDemo3 {
	public static void main(String[] args) {
		Kid3 k = new Kid3();
		k.show();
	}
}

class Dad3 {
	String name = "建霖";
	String superName = "父类中的成员变量";
}

class Kid3 extends Dad3 {
	String name = "四葱";
	
	public void show() {
		System.out.println(super.superName);
		
		String name = "五葱";
		
		//System.out.println(super.name);
		System.out.println(this.name);
		System.out.println(name);
	}
}

Code analysis:Create a parent class - Dad3. The member variables are name and superName. Kid3 also has name in the subclass. If you want to access the member variable name in the subclass , you need to use this, and if you want to access the superName in the parent class in the subclass, you need to use super, but when accessing local variables, you don't need this, and the proximity principle is adopted.

 InheritMember methods in

  • When the subclass has a method that is exactly the same as the parent class, when the subclass object calls the method method, will run the content of the sub class method. Just like the method of parent class is overridden by .
  • This case is methodAnother characteristic:
  • override)
  • overloadoverload

 Characteristics of member methods in inheritance:

If there is no such method in the subclass, call the parent class's

This method is overridden in the subclass and calls the subclass's

Method override (override):In the child parent class, the child class's method is exactly the same as the parent class's method, and the child class overrides the parent class's method (overrides ), when the subclass overrides the method of the parent class, the method of the subclass is called using the subclass object

Method overload (overload):In a class, there are multiple methods with the same name, but their parameters are different (number of parameters, type of parameters, The order of parameters), regardless of the return value

package com.demo02;
/*
 * 继承中成员方法的特点
 * 		子类中没有这个方法,调用父类的
 * 		子类中重写了这个方法,调用子类的
 * 
 
 	方法的重写(override):在子父类当中,子类的方法和父类的完全一样,子类重写了父类的方法(覆盖),当子类重写了父类的方法之后,使用子类对象调用的就是子类的方法
 	方法的重载(overload):在一个类中,有多个重名的方法,但是其参数不一样(参数的个数,参数的类型,参数的顺序),和返回值无关
 
 */
public class ExtendsDemo4 {
	public static void main(String[] args) {
		Kid4 k = new Kid4();
		k.eat();
		k.eat(null);
	}
}

class Dad4 {
	public void eat() {
		System.out.println("小酌两口");
		System.out.println("去睡觉了");
	}
}

class Kid4 extends Dad4 {
	public void eat() {
		super.eat();
		System.out.println("好好吃饭");
	}
	
	public void eat(String name) {
		super.eat();
		System.out.println("好好吃饭1");
	}
}

Code analysis: defines a parent class - Dad4, which defines an eat() method, defines a subclass Kid4, inherits the parent class Dad4, and also defines a The eat() method is consistent with the method of the parent class. Use super to call the method of the parent class, create a class object, and execute the program. The parent class is executed first, and then the subclass is executed.

 Method overriding

  • When a method that is exactly the same as the parent class appears in a subclass, an overwriting operation occurs, also called overwriting or overriding.
  • Can private methods in the parent class be overridden? Subclasses cannot see the methods of the parent class at all
  • In a subclass overriding method, continuing to use the overridden method can be obtained through the super. method name.
  • Notes on coverage:

        – When overriding , the subclass method permissions must be greater than or equal to the parent class method permissions

  • Covered applications:

        The function also defines the content unique to the subclass.

package com.demo03;
/*
 * 	方法重写的应用场景:当父类的方法不能完全满足子类使用,这个时候子类重写父类的方法,
 * 				    并可以在方法中使用关键字super调用父类的方法,这样做即可以保有父类的功能,也可以拥有子类特有的功能
 *  方法重写的注意事项:
 *  			  不能重写父类私有的方法
 *  			 权限必须大于等于父类方法的权限
 *  
 *  注解:@
 *  
 */
public class ExtendsDemo5 {
	public static void main(String[] args) {
		NewPhone np = new NewPhone();
		np.call();
	}
}

//父类
class Phone {
	void call() {
		System.out.println("打电话");
	}
}

//子类
class NewPhone extends Phone {
	
	@Override // 说明方法是重写父类中的方法
	public void call() {
		System.out.println("录音");
		//System.out.println("打电话");
		
		//super.call();
	}
}

Code analysis:First create a parent class - Phone. The parent class's method is call. We then create a subclass and use @Override to rewrite the call method. What is the function type in the parent class, what must be the function type in the subclass; for example: if it is Public in the parent class, the subclass must also be Public.

Constructor method in inheritance

  • When initializing a subclass object, the parent class's construction method will also run. That is because the subclass's construction /span>r ()supe to have an implicit statement in the first lineThe method defaults
  • super(): will access the empty parameter structure in the parent class< a i=4> manufacturing method. And all constructors in subclasses default to the first line of super( < a i=8>)
package com.demo03;
/*
 * 继承中构造方法的执行顺序
 * 			在子父类中,创建子类对象,调用子类的构造方法,
 * 			在子类的构造方法的第一行代码如果没有调用父类的构造或者没有调用子类的其他构造,则默认调用父类无参构造
 * 为什么要调用父类构造?
 * 			因为需要给父类的成员变量初始化
 * 肯定会先把父类的构造执行完毕,再去执行子类构造中的其他代码
 * 
 * 我是父类无参构造 --- 我是子类有参构造 --- 我是子类无参构造
 */
public class ExtendsDemo6 {
	public static void main(String[] args) {
		//Parent d = new Parent();
		Son6 son = new Son6(1);
	}
}

class Parent6 {
	public Parent6() {
		System.out.println("我是父类无参构造");
	}
	
	public Parent6(int num) {
		System.out.println("我是父类有参构造");
	}
}

//子类
class Son6 extends Parent6 {
	public Son6() {
		super(1);//写不写一定会执行父类无参数
		System.out.println("我是子类无参构造");
	}
	
	public Son6(int num) {
		this(1l);
		//会默认调用父类无参构造
		System.out.println("我是子类有参构造");
	}
	
public Son6(long num) {
		//会默认调用父类无参构造
		System.out.println("我是子类有参构造");
	}
}

Code analysis:Whether super() is written in the subclass or not, the parent class's no-parameter construction will be executed. If super(1) is written, the parent class's parameterless construction will be executed. For parameter construction, if we don’t want to call the parameterless constructor in the parent class, we should write this(1), so that the parameterless constructor in the parent class will not be called, but in the end the subclass Son6 is still called. In this way, there must be a subclass method to call the parent class. They cannot be called cyclically. Eventually, one of the subclasses will call the parent class.

result:

 super关键字 

  • The usage of super is similar to this
  • this represents a reference to the object (whoever calls it represents whoever calls it)
  • super represents a reference to the parent class of the current subclass object
  • When a member with the same name appears in a child or parent class, super can be used to distinguish
  • When a subclass wants to call the parent class constructor, it can use the super statement.

superthisdivided

  • this : reference to the object (whoever calls it represents)
  • Use this keyword to reference member variables.
  • Use this keyword to reference other constructors within its own constructor.
  • Use this keyword to reference member methods
  • super : Reference to parent class in the current object.
  • Reference the constructor of the parent class within the constructor of the subclass.
  • Call member methods in the parent class in the subclass.
  • Call member variables in the parent class in the subclass.
package com.demo03;
/*
 * this和super的区别
		this:当前对象的引用
			调用子类的成员变量
			调用子类的成员方法
			在子类的构造方法第一行调用子类其他构造方法
		super:子类对象的父类引用
			调用父类的成员变量
			调用父类的成员方法
			在子类的构造方法第一行调用父类的构造方法
 */
public class ExtendsDemo7 {
	public static void main(String[] args) {
		Son z = new Son();
		z.function();
	}
}

//父类
class Parent {
	int num = 10;
	
	//无参构造方法
	public Parent() {
		System.out.println("我是父类无参构造");
	}
	// 有参构造方法
	public Parent(int num) {
		System.out.println("我是父类有参构造");
	}
	// 普通方法
	public void method() {
		System.out.println("我是父类的方法");
	}
}


// 子类
class Son extends Parent {
	int num = 30;
	
	public Son() {
		this(1);//第一行不调用子类其他构造或者是父类构造,默认调用父类无参构造
		//super();
		System.out.println("我是子类无参构造");
	}
	
	public Son(int num) {
		System.out.println("我是子类有参构造");
	}
	
	public void method() {
		System.out.println("我是子类的方法");
	}
	
	public void function() {
		//this.num = 50;
		//System.out.println(num);
		//this.method();
		
		//super.num = 40;
		super.method();
		
		//System.out.println(super.num);
		//System.out.println(this.num);
	}
}


Code analysis:We new a subclass object. When we see this(1), the subclass has a parameter constructor, but there is no super() in it. The default is the parent The parameterless construction of the class, then execute the I am subclass parameterized constructor, return after execution, execute the I am subclass parameterized constructor, the construction method is completed, and then execute z.function.

The results show that:

InheritedAdvantages and Disadvantages

  • shortcoming:

        –The coupling of the class has been enhanced

        –Development principles: high cohesion and low coupling

        –Cohesion: the ability to complete something by oneself

        –Coupling: the relationship between classes

Guess you like

Origin blog.csdn.net/zywcxz/article/details/128849607