[Java Fundamentals] Chapter 5_Object-Oriented (Part 2)-1: Inheritance, Rewriting, 4 Permission Modifiers, super Keyword, Subclass Object Instantiation

PPT link: Click here

1. The second object-oriented feature: inheritance

1.1. Understanding of inheritance

Why should there be inheritance

  • When the same attributes and behaviors exist in multiple classes, extract these contents into a single class, then multiple classes do not need to define these attributes and behaviors, just inherit that class

Inherited Benefits

  • Reduced code redundancy and improved code reusability
  • Easy to expand functions
  • Provides a prerequisite for the use of polymorphism in the future

inherited format

  • class A extends B{}

    • A: subclass, derived class, subclass
    • B: parent class, super class, base class, superclass
  • Embodiment: Once the subclass A inherits the parent class, the structure declared in the parent class B is obtained in the subclass A: attributes and methods. In particular, for the properties or methods declared as private in the parent class, after the subclass inherits the parent class, it still thinks that it has obtained the private structure in the parent class. Only because of the impact of encapsulation, the subclass cannot directly call the structure of the parent class.

  • After the subclass inherits the parent class, it can also declare its own unique properties or methods to realize the expansion of functions

  • The relationship between subclasses and parent classes: different from the relationship between subsets and collections

Rules about Inheritance in Java

  • A class can be inherited by multiple classes

  • Single inheritance of classes in Java: a class can only have one parent class

  • Child parent class is a relative concept

  • The parent class directly inherited by the child class is called the direct parent class. Indirectly inherited parent class, called indirect parent class

  • After the subclass inherits the parent class, it obtains the properties and methods declared in the direct parent class and all indirect parent classes

illustrate

  • If we do not explicitly declare a parent class of a class, then this class inherits from the java.lang.Object class
  • All java classes (except the java.long.Object class) inherit directly or indirectly from the java.lang.Object class
  • Means, all java classes have the functionality declared by the java.lang.Object class

rules of inheritance

Single Inheritance vs Multi-Level Inheritance

1.2. Practice

(1)define a ManKind class, including
	Member variables int sex and int salary
	method void manOrWoman(): according to sex value shows " man"(sex==1)or" woman"(sex==0)
	method void employeed(): according to salary value shows " no job"(salary==0)or" job"(salary!=0)
(2)define class Kids inherit ManKind,and include
	Member variables int yearsOld;
	method printAge()Print yearsOld the value of
(3)define class KidsTest,in class main instantiated in the method Kids Object someKid,Use this object to access member variables and methods of its parent class

[Code]

public class ManKind {
	private int sex;//gender
	private int salary;//salary
	
	public ManKind() { 
	}
	public ManKind(int sex, int salary) {
		this.sex = sex;
		this.salary = salary;
	}

	public void manOrWoman(){
		if(sex == 1){
			System.out.println("man");
		}else if(sex == 0){
			System.out.println("woman");
		}
	}
	
	public void employeed(){
//		if(salary == 0){
//			System.out.println("no job");
//		}else{
//			System.out.println("job");
//		}
		//or
		String jobInfo = (salary == 0)? "no job" : "job";
		System.out.println(jobInfo);
	}

	public int getSex() {
		return sex;
	}
	public void setSex(int sex) {
		this.sex = sex;
	}

	public int getSalary() {
		return salary;
	}
	public void setSalary(int salary) {
		this.salary = salary;
	}
}
public class Kids extends ManKind{
	private int yearsOld;
	
	public Kids() {
	}
	public Kids(int yearsOld) {//Assign values ​​to properties with constructors
		this.yearsOld = yearsOld;
	}

	public void printAge(){
		System.out.println("I am " + yearsOld + " years old.");
	}

	public int getYearsOld() {
		return yearsOld;
	}
	public void setYearsOld(int yearsOld) {
		this.yearsOld = yearsOld;
	}
    
	/*
	 * Modify the class Kids defined in the exercise, redefine the employee() method in Kids,
	 * Override the employee() method defined in the parent class ManKind, and output "Kids should study and no job."
	 */
	public void employeed() {//method override
		System.out.println("Kids should study and no job.");
	}
}
public class KidsTest {
	public static void main(String[] args) {
		Kids someKid = new Kids(12);
		someKid.printAge();//I am 12 years old.
		
		someKid.setSalary(0);
		someKid.setSex(1);
		
		someKid.employeed();//Kids should study and no job.
		someKid.manOrWoman();//man
	}
}

2. Method rewriting (override)

  • Override: After the subclass inherits the parent class, it can override the method in the parent class
  • Application: After rewriting, when a subclass object is created and a method with the same name and parameters in the subclass is called through the subclass object, the subclass rewrites the method of the parent class is executed. That is, when the program is executed, the method of the subclass will override the method of the parent class

overridden regulations

  • Method declaration:

    //1. Paste the first line of the method of the parent class directly, and directly write the method body
    	public void walk(int distance){
    		System.out.println("overridden method");
    	}
    	
    //2. Directly enter the method name of the parent class, Alt + /, select to generate
    	@Override
    	public void walk(int distance) {
    		System.out.println("Automatic generated");
    	}
    
  • The convention is commonly known as: the method in the subclass is called the overridden method, and the method in the parent class is called the overridden method

Precautions

  • The method name and formal parameter list of the method overridden by the subclass must be the same as the method name and formal parameter list of the overridden method of the parent class

  • The access permissions used by the methods rewritten by the subclass are greater than or equal to the access permissions of the overridden methods of the parent class (permission: subclass >= parent class)

    Special case: subclasses cannot override methods declared as private permissions in the parent class

  • return type

    • The return value type of the overridden method of the parent class is void, and the return value type of the method overridden by the subclass can only be void
    • The return value type of the overridden method of the parent class is A type, and the return value type of the method overridden by the subclass can be A class or a subclass of A class
    • If the return value type of the overridden method of the parent class is a basic data type (such as double), the return value type of the method overridden by the subclass must be the same basic data type (must be double)
  • The exception thrown by the subclass method is less than or equal to the exception thrown by the overridden method of the parent class (exception: subclass <= parent class)

Note: The method with the same name and the same parameters in the subclass and the parent class must be declared as non-static (that is, overridden) or static (not overridden) at the same time. Because the static method belongs to the class, the subclass cannot override the method of the parent class ----- To be inherited, the method of the parent class cannot be decorated with final, private, or static

Interview question: Differentiate between method overloading and overriding

  1. Method overloading (Overloading) is a class that defines multiple methods with the same name, but the number of parameters is different or the number is the same but the type and order are different
  2. Method overriding (Overriding) is a method that exists in the subclass with the same name as the method of the parent class, and the number and type of parameters are the same, and the return value is also the same.
  3. Method rewriting and overloading are different manifestations of java polymorphism. Method overloading is a polymorphic manifestation of a class, while method rewriting is a polymorphic manifestation of subclasses and parent classes.

3. Four access modifiers

The Java permission modifiers public, protected, default (default), and private are placed before the member definition of the class to limit the access rights of the object to the member of the class

Only public and default (default) can be used for permission modification of class class

  • public classes can be accessed anywhere

  • The default class can only be accessed by classes inside the same package

package com.atguigu.java2;

public class Order {
	
	private int orderPrivate;
	int orderDefault;
	protected int orderProtected;
	public int orderPublic;
	
	private void methodPrivate(){
		orderPrivate = 1;
		orderDefault = 2;
		orderProtected = 3;
		orderPublic = 4;
	}
	void methodDefault(){
		orderPrivate = 1;
		orderDefault = 2;
		orderProtected = 3;
		orderPublic = 4;
	}
	protected void methodProtected(){
		orderPrivate = 1;
		orderDefault = 2;
		orderProtected = 3;
		orderPublic = 4;
	}
	
	public void methodPublic(){
		orderPrivate = 1;
		orderDefault = 2;
		orderProtected = 3;
		orderPublic = 4;
	}
}

different classes in the same package

package com.atguigu.java2;

public class OrderTest {
	public static void main(String[] args) {
		Order order = new Order();
		
		order.orderDefault = 1;
		order.orderProtected = 2;
		order.orderPublic = 3;
		
		order.methodDefault();
		order.methodProtected();
		order.methodPublic();
		
		//Other classes in the same package cannot call private properties and methods in the Order class
//		order.orderPrivate = 4;
//		order.methodPrivate();
	}
}

Subclasses under different packages

package com.atguigu.java3;

import com.atguigu.java2.Order;//Use classes under different packages

public class SubOrder extends Order {
	
	public void method(){
		orderProtected = 1;
		orderPublic = 2;
		
		methodProtected();
		methodPublic();
		
		//In subclasses of different packages, the attributes and methods declared as private and default permissions in the Order class cannot be called
//		orderDefault = 3;
//		orderPrivate = 4;
//		methodDefault();
//		methodPrivate();
	}
}

Non-subclasses under different packages

package com.atguigu.java3;

import com.atguigu.java2.Order;

public class OrderTest {
	public static void main(String[] args) {
		
		Order order = new Order();
		order.orderPublic = 1;
		order.methodPublic();
		
		//Ordinary classes (non-subclasses) under different packages must use the Order class, and cannot call attributes and methods declared as private, default, and protected permissions
//		order.orderPrivate = 2;
//		order.orderDefault = 3;
//		order.orderProtected = 4;
//		order.methodPrivate();
//		order.methodDefault();
//		order.methodProtected();
	}
}

4. super keyword

4.1, the use of super

  • super is understood as: the parent class
  • super can be used to call: properties, methods, constructors

use of super

  • We can explicitly call the properties or methods declared in the parent class by means of "super. property" or "super. method" in the method or constructor of the subclass. However, under normal circumstances, we are used to omit this "super."
  • Special case 1: When a property with the same name is defined in the subclass and the parent class, if we want to call the property declared in the parent class in the subclass, we must explicitly use the "super. property" method to indicate the calling is an attribute declared in the parent class
  • Special case 2: When the subclass overrides the method in the parent class, when we want to call the overridden method in the parent class in the method of the subclass, we must explicitly use the "super. Calling the overridden method in the parent class

super calls the constructor

  • We can explicitly use the "super (parameter list)" method in the constructor of the subclass to call the specified constructor declared in the parent class
  • The use of "super( parameter list)" must be declared on the first line of the subclass constructor
  • In the constructor of the class, we can only choose one of "this (parameter list)" or "super (parameter list)", and cannot appear at the same time
  • In the first line of the constructor, if there is no explicit declaration of "this (parameter list)" or "super (parameter list)", the default call is the empty parameter constructor in the parent class: super()
  • Among the multiple constructors of the class, at least one of the constructors of the class uses "super (parameter list)" to call the constructor in the parent class

Note: When the subclass inherits the parent class, because the subclass has a null parameter constructor by default, and super() (the parent class's null parameter constructor) is called by default in the subclass's null parameter constructor, if the parent class only has A constructor with parameters but no constructor with empty parameters will report an error

  • Solution 1: Write a null parameter constructor in the parent class
  • Solution 2: There is a parameter constructor written in the subclass, and instead of super(), let it call the specified parent class constructor super (parameter 1, parameter 2)
public class Person {
	String name;
	int age;
	int id = 1001;
	
	public Person(){
		System.out.println("i am everywhere");
	}
	public Person(String name){
		this.name = name;
	}
	public Person(String name,int age){
		this(name);
		this.age = age;
	}
	
	public void eat(){
		System.out.println("people eating");
	}
	
	public void walk(){
		System.out.println("people walking");
	}
}
public class Student extends Person{
	String major;
	int id = 1002;//student ID
	
	public Student(){
	}
	public Student(String name,int age,String major){
//		this.age = age;
//		this.name = name;
		super(name,age);//Call the designated initializer of the parent class
		this.major = major;
	}
	public Student(String major){
		this.major = major;
	}
	
	public void eat(){
		System.out.println("Students eat more nutritious food");
	}
	
	public void Study(){
		System.out.println("students, learn knowledge.");
		this.eat();
		super.eat();//Call the overridden method in the parent class, not the method in the subclass
		super.walk();//The methods that are not overridden in the child parent class can be called with "this." or "super."
	}
    
	public void show(){
		System.out.println("name = " + this.name + ",age = " + super.age);
		System.out.println("id = " + this.id);	
		System.out.println("id = " + super.id);
	}
}

The difference between this and super

  • this.: first find the attribute in the subclass, and then find the attribute from the parent class or indirect parent class if it cannot be found

  • super.: first find the attribute in the parent class, and then find the attribute from its parent class or indirect parent class if it cannot be found

4.2. Practice

Experiment - Inheritance & super.pdf

[Code]

/*
 * Write a demo account named Account class. The properties and methods of this class are shown in the figure below.
 * The attributes included in this class: account id, balance balance, annual interest rate annualInterestRate;
 * Included methods: accessor methods (getter and setter methods),
 * The method getMonthlyInterest() that returns the monthly interest rate,
 * Withdrawal method withdraw(), deposit method deposit().
 */
public class Account {

	private int id;	//account
	private double balance;	//balance
	private double annualInterestRate;	//annual interest rate
	
	public Account(int id, double balance, double annualInterestRate) {
		super();
		this.id = id;
		this.balance = balance;
		this.annualInterestRate = annualInterestRate;
	}

	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}

	public double getBalance() {
		return balance;
	}
	public void setBalance(double balance) {
		this.balance = balance;
	}

	public double getAnnualInterestRate() {
		return annualInterestRate;
	}
	public void setAnnualInterestRate(double annualInterestRate) {
		this.annualInterestRate = annualInterestRate;
	}
	
	public double getMonthlyInterest(){	//Method that returns the monthly interest rate
		return annualInterestRate / 12;
	}
	
	public void withdraw (double amount){	//Withdrawal method
		if(balance >= amount){
			balance -= amount;
			return;
		}
		System.out.println("Insufficient balance");
	}
	
	public void deposit (double amount){	//deposit method
		if(amount > 0){
			balance += amount;
		}
	}
}
/*
 * Write a user program to test the Account class. In the user program,
 * Create an Account object with an account number of 1122, a balance of 20000, and an annual interest rate of 4.5%.
 * Use the withdraw method to withdraw 30,000 yuan and print the balance. Then use the withdraw method to withdraw 2,500 yuan,
 * Use the deposit method to deposit 3,000 yuan, and then print the balance and monthly interest rate.
 */
public class AccountTest {
	public static void main(String[] args) {
		Account acct = new Account(1122,20000,0.045);
		
		acct.withdraw(30000);
		System.out.println("Your account balance is:" + acct.getBalance());
		acct.withdraw(2500);
		System.out.println("Your account balance is:" + acct.getBalance());
		acct.deposit(3000);
		System.out.println("Your account balance is:" + acct.getBalance());

		System.out.println("The monthly interest rate is: " + (acct.getAnnualInterestRate() * 100) + "%");
	}
}
/*
 * Create a subclass CheckAccount of the Account class to represent an overdraft account, and define an attribute overdraft in the account to represent the overdraft limit.
 * Override the withdraw method in the CheckAccount class, and its algorithm is as follows:
 * If (withdrawal amount < account balance), you can withdraw directly
 * If (withdrawal amount > account balance), calculate the overdraft amount required to determine whether the overdraft amount overdraft is sufficient to cover the overdraft needs
 * if it is possible
 * 		Change the account balance to 0 to offset the overdraft amount
 * if it is not possible
 * 		Prompt the user to exceed the limit of the overdraft limit
 */
public class CheckAccount extends Account{

	private double overdraft;	//Represents the overdraft limit
	
	public CheckAccount(int id, double balance, double annualInterestRate,double overdraft){
//      this.id = id;
//		this.balance = balance;
//		this.annualInterestRate = annualInterestRate;
		super(id, balance, annualInterestRate);//You can only use super to call the parent class constructor, which is wrong because the three variables have been privatized
		this.overdraft = overdraft;
	}
	
	public double getOverdraft() {
		return overdraft;
	}
	public void setOverdraft(double overdraft) {
		this.overdraft = overdraft;
	}

	@Override
	public void withdraw(double amount) {
		if(getBalance() >= amount){//enough balance to spend
			//method one
//			setBalance(getBalance() - amount); 
			//way two
			super.withdraw(amount);//Understanding: Use super.withdraw() to call the withdrawal method in the parent class to directly change the balance
		}else if(overdraft >= amount - getBalance()){//Insufficient balance, can overdraft
			overdraft -= (amount - getBalance());//Note: setBalance() is written below, otherwise getBalance() is 0
            
//			setBalance(0);
			//or
			super.withdraw(getBalance());//take all the money
		}else{//overdraft limit exceeded
			System.out.println("Overdraft limit exceeded!");
		}
	}
}
/*
 * Write a user program to test the CheckAccount class. In the user program,
 * Create an account number 1122, balance 20000, annual interest rate 4.5%,
 * A CheckAccount object with an overdraft limit of 5,000 yuan.
 * Use the withdraw method to withdraw 5,000 yuan, and print the account balance and overdraft amount.
 * Then use the withdraw method to withdraw 18,000 yuan, and print the account balance and overdraft amount.
 * Then use the withdraw method to withdraw 3,000 yuan, and print the account balance and overdraft amount.
 * 
 */
public class CheckAccountTest {
	public static void main(String[] args) {
		CheckAccount cat = new CheckAccount(1122,20000,0.045,5000);
		
		cat.withdraw(5000);
		System.out.println("Your account balance is: " + cat.getBalance());
		System.out.println("Your overdraft limit is: " + cat.getOverdraft());
		
		cat.withdraw(18000);
		System.out.println("Your account balance is: " + cat.getBalance());
		System.out.println("Your overdraft limit is: " + cat.getOverdraft());
		
		cat.withdraw(3000);
		System.out.println("Your account balance is: " + cat.getBalance());
		System.out.println("Your overdraft limit is: " + cat.getOverdraft());
	}
}

5. Subclass object instantiation process

As a result (inheritance)

  • After the subclass inherits the parent class, it obtains the properties or methods declared in the parent class
  • In the object of the created subclass, in the heap space, all the attributes declared in the parent class will be loaded

From the process point of view

  • When we create a subclass object through the constructor of the subclass, we must directly or indirectly call the constructor of its parent class until the constructor of the empty parameter in the java.lang.Object class is called. Just because all parent class structures have been loaded, you can see that there are parent class structures in memory, and subclass objects can be considered to call

Clear: Although the constructor of the parent class is called when the subclass object is created, an object has been created from beginning to end, which is the subclass object of new

Natural selection, survival of the fittest, come on! ! !

Tags: Java Eclipse IDEA

Posted by deolsabh on Wed, 30 Nov 2022 13:12:40 +0530