JAVA foundation-Chapter 9 inheritance, super, this, abstract class

Today's content

Three characteristics-inheritance
method rewriting

super关键字
this关键字
抽象类

teaching objectives

Can explain the class name as the parameter and return value type
Can write the inheritance format of the class
Can tell the characteristics of inheritance
Can tell the member characteristics of the subclass calling the parent class
Can tell the concept of method override
Can tell the problem that super can solve
Describe the concept of abstract methods
Write the format of the abstract class Write the format of the
abstract method
Can tell the meaning of the abstract method of the parent class
Can complete the code logic of the red envelope case

Chapter 1 Succession

1. 1 Overview

Origin

When the same attributes and behaviors exist in multiple classes, these contents are extracted into a single class, so multiple classes do not need to define these attributes and behaviors, as long as

Just inherit that one class. as the picture shows:

Among them, multiple classes can be called subclasses, and a single class is called a parent class, superclass or base class.

Inheritance describes the belonging relationship between things, this relationship is: is-a relationship. For example, in the picture, rabbits are herbivores, and herbivores are animals
. It can be seen that the parent class is more general and the child class is more specific. Through inheritance, we can form a relationship system between many things.

definition

Inheritance: the subclass inherits the properties and behaviors of the parent class, so that the subclass object has the same properties and behaviors as the parent class. The subclass can directly
access the non-private properties and behaviors in the parent class.

benefit

  1. Improve code reusability.
  2. The relationship between class and class is the premise of polymorphism.

1. 2 Inherited format

Through the extends keyword, you can declare that a subclass inherits another parent class. The definition format is as follows:

Inheritance demonstration, the code is as follows:

class 父类 {
...
}
class 子类 extends 父类 {
...
}

/*

* 定义员工类Employee,做为父类

1. 3 Features after inheritance-member variables

When the relationship between the classes is formed, what impact does the member variables in each class have?

Member variables do not have the same name

If a member variable with no duplicate name appears in the parent class of the subclass, the access at this time has no effect. code show as below:

*/

class Employee {
String name; // 定义name属性
// 定义员工的工作方法
public void work() {
System.out.println("尽心尽力地工作");
}
}
/*
* 定义讲师类Teacher 继承 员工类Employee
*/
class Teacher extends Employee {
// 定义一个打印name的方法
public void printName() {
System.out.println("name=" + name);
}
}
/*
* 定义测试类
*/
public class ExtendDemo 01  {
public static void main(String[] args) {
// 创建一个讲师类对象
Teacher t = new Teacher();
// 为该员工类的name属性进行赋值
t.name = "小明";
// 调用该员工的printName()方法
t.printName(); // name = 小明
// 调用Teacher类继承来的work()方法
t.work(); // 尽心尽力地工作
}
}
class Fu {
// Fu中的成员变量。
int num =  5 ;
}
class Zi extends Fu {
// Zi中的成员变量

Member variable has the same name

If a member variable with the same name appears in the parent class of the subclass, the access at this time will have an impact. code show as below:

// Zi中的成员变量
int num 2  =  6 ;
// Zi中的成员方法
public void show() {
// 访问父类中的num,
System.out.println("Fu num="+num); // 继承而来,所以直接访问。
// 访问子类中的num 2
System.out.println("Zi num 2 ="+num 2 );
}
}
class ExtendDemo 02  {
public static void main(String[] args) {
// 创建子类对象
Zi z = new Zi();
// 调用子类中的show方法
z.show();
}
}
演示结果:
Fu num =  
Zi num 2  =  
class Fu {
// Fu中的成员变量。
int num =  5 ;
}
class Zi extends Fu {
// Zi中的成员变量
int num =  6 ;
public void show() {
// 访问父类中的num
System.out.println("Fu num=" + num);
// 访问子类中的num
System.out.println("Zi num=" + num);
}
}
class ExtendsDemo 03  {
public static void main(String[] args) {
// 创建子类对象
Zi z = new Zi();
// 调用子类中的show方法
z.show();
}
}
演示结果:
Fu num =  
Zi num =  

When a member variable with the same name appears in the child and parent class, when you need to access the non-private member variable in the parent class in the child class, you need to use the super keyword to modify the
member variable of the parent class, similar to the this you learned before.

Use format:

The subclass method needs to be modified, the code is as follows:

小贴士:Fu 类中的成员变量是非私有的,子类中可以直接访问。若Fu 类中的成员变量私有了,子类是不能
直接访问的。通常编码时,我们遵循封装的原则,使用private修饰成员变量,那么如何访问父类的私有成员
变量呢?对!可以在父类中提供公共的getXxx方法和setXxx方法。

1.4 Features after inheritance-member method

When a relationship occurs between classes, what influence does the member methods in each class have?

Member method does not have the same name

If there is a member method with no duplicate name in the parent class of the subclass, the call at this time has no effect. When an object calls a method, it will first look for any correctness in the subclass

If the corresponding method exists in the subclass, the method in the subclass will be executed. If the subclass does not exist, the corresponding method in the parent class will be executed. code show as below:

super.父类成员变量名
class Zi extends Fu {
// Zi中的成员变量
int num =  6 ;
public void show() {
//访问父类中的num
System.out.println("Fu num=" + super.num);
//访问子类中的num
System.out.println("Zi num=" + this.num);
}
}
演示结果:
Fu num =  
Zi num =  
class Fu{
public void show(){
System.out.println("Fu类中的show方法执行");
}
}
class Zi extends Fu{
public void show 2 (){
System.out.println("Zi类中的show 2 方法执行");
}
}
public class ExtendsDemo 04 {
public static void main(String[] args) {
Zi z = new Zi();
//子类中没有show方法,但是可以找到父类方法去执行
z.show();

Member method with the same name-Override

If there is a member method with the same name in the parent class of the subclass, the access at this time is a special case, which is called method override (Override).

方法重写 :子类中出现与父类一模一样的方法时(返回值类型,方法名和参数列表都相同),会出现覆盖效
果,也称为重写或者复写。声明不变,重新实现。

code show as below:

Rewritten application

Subclasses can define their own specific behaviors as needed. Not only inherited the function name of the parent class, but also re-implement the parent class method according to the needs of the child class, from

And to expand and enhance. For example, the new mobile phone adds the function of displaying the avatar of the caller ID, the code is as follows:

z.show();
z.show 2 ();
}
}
class Fu {
public void show() {
System.out.println("Fu show");
}
}
class Zi extends Fu {
//子类重写了父类的show方法
public void show() {
System.out.println("Zi show");
}
}
public class ExtendsDemo 05 {
public static void main(String[] args) {
Zi z = new Zi();
// 子类中有show方法,只执行重写后的show方法
z.show(); // Zi show
}
}
class Phone {
public void sendMessage(){
System.out.println("发短信");
}
public void call(){
System.out.println("打电话");
}
public void showNum(){
System.out.println("来电显示号码");
}
}
小贴士:这里重写时,用到super.父类成员方法,表示调用父类的成员方法。

Precautions

1. The method of the subclass overrides the method of the parent, and the authority must be greater than or equal to the authority of the parent.

2. The subclass method overrides the parent class method, and the return value type, function name and parameter list must be exactly the same.

1.5 Features after inheritance-construction method

When there are relationships between classes, what are the effects of the construction methods among them?

First of all, we have to recall two things, the definition format and role of the construction method.

1. The name of the constructor is consistent with the class name. Therefore, the subclass cannot inherit the construction method of the parent class.

2. The role of the constructor is to initialize member variables. Therefore, during the initialization of the subclass, the initialization of the parent must be executed first. Construction of subclasses

造方法中默认有一个super() ,表示调用父类的构造方法,父类成员变量初始化后,才可以给子类使用。代
码如下:

//Smartphone

class NewPhone extends Phone {
//重写父类的来电显示号码功能,并增加自己的显示姓名和图片功能
public void showNum(){
//调用父类已经存在的功能使用super
super.showNum();
//增加自己特有显示姓名和图片功能
System.out.println("显示来电姓名");
System.out.println("显示头像");
}
}
public class ExtendsDemo 06  {
public static void main(String[] args) {
// 创建子类对象
NewPhone np = new NewPhone();
// 调用父类继承而来的方法
np.call();
// 调用子类重写的方法
np.showNum();
}
}
class Fu {
private int n;
Fu(){
System.out.println("Fu()");
}
}

1. 6 super and this

Parent space is generated prior to subclass objects

Each time a subclass object is created, the parent class space is initialized first, and then the subclass object itself is created. The purpose is that the subclass object contains its corresponding parent empty

It can contain members of its parent class. If the members of the parent class are not privately modified, the subclass can use the members of the parent class at will. When the code is reflected in the subclass's construction
method call, the parent class's construction method must be called first. The understanding diagram is as follows:

The meaning of super and this

super :代表父类的存储空间标识(可以理解为父亲的引用)。
this :代表当前对象的引用(谁调用就代表谁)。

The usage of super and this

1. Visiting members

class Zi extends Fu {
Zi(){
// super(),调用父类构造方法
super();
System.out.println("Zi()");
}
}
public class ExtendsDemo 07 {
public static void main (String args[]){
Zi zi = new Zi();
}
}
输出结果:
Fu()
Zi()

Usage demonstration, the code is as follows:

2. Access to the construction method

子类的每个构造方法中均有默认的super(),调用父类的空参构造。手动调用父类构造会覆盖默认的super()。
super() 和 this() 都必须是在构造方法的第一行,所以不能同时出现。

1. 7 inherited characteristics

1. Java只支持单继承,不支持多继承。
this.成员变量 ‐‐ 本类的
super.成员变量 ‐‐ 父类的
this.成员方法名() ‐‐ 本类的
super.成员方法名() ‐‐ 父类的
class Animal {
public void eat() {
System.out.println("animal : eat");
}
}
class Cat extends Animal {
public void eat() {
System.out.println("cat : eat");
}
public void eatTest() {
this.eat(); // this 调用本类的方法
super.eat(); // super 调用父类的方法
}
}
public class ExtendsDemo 08  {
public static void main(String[] args) {
Animal a = new Animal();
a.eat();
Cat c = new Cat();
c.eatTest();
}
}
输出结果为:
animal : eat
cat : eat
animal : eat
this(...) ‐‐ 本类的构造方法
super(...) ‐‐ 父类的构造方法
2. Java支持多层继承(继承体系)。
顶层父类是Object类。所有的类默认继承Object,作为父类。
3. 子类和父类是一种相对的概念。

Chapter 2 Abstract Class

2. 1 Overview

Origin

The methods in the parent class are overridden by its subclasses, and their respective implementations are different. Then the method declaration and method body of the parent class, only the declaration has

Meaning, and the method subject has no meaning. We call methods without method bodies abstract methods. Java syntax stipulates that
a class that contains abstract methods is an abstract class.

definition

Abstract method: A method without a method body.

Abstract class: A class that contains abstract methods.

2. 2 abstract use format

Abstract method

Use the abstract keyword to modify the method, and the method becomes an abstract method. The abstract method contains only a method name, but no method body.

Definition format:

Code example:

Abstract class

If a class contains abstract methods, then the class must be an abstract class.

Definition format:

//A class can only have one parent class, not multiple parent classes.

class C extends A{} //ok
class C extends A,B... //error
class A{}
class B extends A{}
class C extends B{}
修饰符 abstract 返回值类型 方法名 (参数列表);
public abstract void run();

Code example:

Abstract use

Subclasses that inherit the abstract class must override all the abstract methods of the parent class. Otherwise, the subclass must also be declared as an abstract class. Ultimately, there must be subclasses that implement the parent

The abstract method of the class, otherwise, the object cannot be created from the initial parent class to the final subclass, meaningless.

Code example:

The method rewriting at this time is the complete realization of the abstract method of the parent class by the subclass. The operation of this method rewriting is also called the realization method.

2. 3 matters needing attention

Regarding the use of abstract classes, the following are grammatical details to pay attention to. Although there are many entries, if you understand the essence of abstraction, you don't need to memorize it by rote.

1. An abstract class cannot create an object. If it is created, the compilation fails and an error is reported. Only objects of non-abstract subclasses can be created.

Understanding: Assuming that an object of an abstract class is created, abstract methods are called, and abstract methods have no concrete method body and are meaningless.

2. In the abstract class, there can be a construction method, which is used to initialize the members of the parent class when the subclass creates an object.

理解:子类的构造方法中,有默认的super(),需要访问父类构造方法。
3. 抽象类中,不一定包含抽象方法,但是有抽象方法的类必定是抽象类。
abstract class 类名字 {
}
public abstract class Animal {
public abstract void run();
}
public class Cat extends Animal {
public void run (){
System.out.println("小猫在墙头走~~~");
}
}
public class CatTest {
public static void main(String[] args) {
// 创建子类对象
Cat c = new Cat();
// 调用run方法
c.run();
}
}
输出结果:
小猫在墙头走~~~

Understanding: The purpose of an abstract class that does not contain abstract methods is not to let the caller create objects of this type, and is usually used for some special class structure design.

meter.

4. The subclass of the abstract class must rewrite all the abstract methods in the abstract parent class, otherwise, the compilation fails and an error is reported. Unless the subclass is also abstract

class.

Understanding: Assuming that all abstract methods are not rewritten, the class may contain abstract methods. Then after creating the object, call the abstract method, there is no

significance.

Chapter III Comprehensive Cases of Succession

3. 1 Comprehensive case: the group owner sends ordinary red envelopes

The group owner sends ordinary red envelopes. If a group has multiple members, the group owner will send ordinary red envelopes to the members. The rules of ordinary red envelopes:

1. 群主的一笔金额,从群主余额中扣除,平均分成n等份,让成员领取。
2. 成员领取红包后,保存到成员余额中。

Please complete the definition of all classes in the case and the inheritance relationship between the specified classes according to the description, and complete the red envelope operation.

3. 2 case analysis

According to the description and analysis, the following inheritance system is derived:

3. 3 case realization

Define user class:

public class User {
// 成员变量
private String username; // 用户名
private double leftMoney; // 余额

// Construction method

Define the group leader class:

public User() { }
public User(String username, double leftMoney) {
this.username = username;
this.leftMoney = leftMoney;
}
// get/set方法
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public double getLeftMoney() {
return leftMoney;
}
public void setLeftMoney(double leftMoney) {
this.leftMoney = leftMoney;
}
// 展示信息的方法
public void show() {
System.out.println("用户名:"+ username +" , 余额为:" + leftMoney + "元");
}
}
public class QunZhu extends User {
// 添加构造方法
public QunZhu() {
}
public QunZhu(String username, double leftMoney) {
// 通过super 调用父类构造方法
super(username, leftMoney);
}
/*
群主发红包,就是把一个整数的金额,分层若干等份。
        1 .获取群主余额,是否够发红包.
不能则返回null,并提示.
能则继续.
        2 .修改群主余额.
        3 .拆分红包.
            3. 1 .如果能整除,那么就平均分。
            3. 2 .如果不能整除,那么就把余数分给最后一份。
*/
public ArrayList<Double> send(int money, int count) {
// 获取群主余额
double leftMoney = getLeftMoney();
if(money > leftMoney) {

Define the member class:

return null;
}
// 修改群主余额的
setLeftMoney(leftMoney ‐ money);
// 创建一个集合,保存等份金额
ArrayList<Double> list = new ArrayList<>();
// 扩大 100 倍,相当于折算成'分'为单位,避免小数运算损失精度的问题
money = money *  100 ;
// 每份的金额
int m = money / count;
// 不能整除的余数
int l = money % count;
// 无论是否整除,n‐ 1 份,都是每份的等额金额
for (int i =  0 ; i < count ‐  1 ; i++) {
// 缩小 100 倍,折算成 '元'
list.add(m /  100. 0 );
}
// 判断是否整除
if (l ==  0 ) {
// 能整除, 最后一份金额,与之前每份金额一致
list.add(m /  100. 0 );
} else {
// 不能整除, 最后一份的金额,是之前每份金额+余数金额
list.add((m + l) /  100. 00 );
}
// 返回集合
return list;
}
}
public class Member extends User {
public Member() {
}
public Member(String username, double leftMoney) {
super(username, leftMoney);
}
// 打开红包,就是从集合中,随机取出一份,保存到自己的余额中
public void openHongbao(ArrayList<Double> list) {
// 创建Random对象
Random r = new Random();
// 随机生成一个角标
int index = r.nextInt(list.size());
// 移除一个金额

Define the test class:

After class, students are asked to think about and complete the expansion requirements.

Case extension:

1. What if the member’s balance is not 0?

Double money = list.remove(index);
// 直接调用父类方法,设置到余额
setLeftMoney( money );
}
}
public class Test {
public static void main(String[] args) {
// 创建一个群主对象
QunZhu qz = new QunZhu("群主" ,  200 );
// 创建一个键盘录入
Scanner sc = new Scanner();
System.out.println("请输入金额:");
int money = sc.nextInt();
System.out.println("请输入个数:");
int count = sc.nextInt();
// 发送红包
ArrayList<Double> sendList = s.send(money,count);
// 判断,如果余额不足
if(sendList == null){
System.out.println(" 余额不足...");
return;
}
// 创建三个成员
Member m = new Member();
Member m 2  = new Member();
Member m 3  = new Member();
// 打开红包
m.openHongbao(sendList);
m 2 .openHongbao(sendList);
m 3 .openHongbao(sendList);
// 展示信息
qz.show();
m.show();
m 2 .show();
m 3 .show();
}
}

2. What if the group owner wants to enter the amount with decimals?

Guess you like

Origin blog.csdn.net/weixin_43419256/article/details/108198479