7, Object oriented programming (in)

  This article is based on Video Science, and the sources are as follows:

Tutorial source:

Java basic to advanced_ Zero foundation self-study Java – shangsilicon Valley – song Hongkang
Tutorial video address:

 Java basic to advanced_ Zero foundation self-study Java -- still Silicon Valley -- song Hongkang_ Beep beep beep_ bilibilihttps://www.bilibili.com/video/BV1ny4y1Y7CW

1. Common shortcut keys for eclipse 1

2. Common shortcut keys for eclipse 2

3. Common shortcut keys 3

  • Complete the code: Alt + / or change it to windows ------ preference ------ Java ------ editor ------ content assist ------ trigger for Java. Change the content in trigger for Java to qwertyuiopasdfghjklzxcvbnm., then any content is prompted

  • How to modify shortcut keys: Windows - Preference - Search (keys) - modify
package com.atshangguigu.java;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/* Eclispse Some shortcut keys in the process of using
 * 1.Quick completion code declaration: Alt +/
 * 2.Quick fix: Ctrl + 1
 * 3.Batch package Guide: Ctrl + shift + o
 * Due to the existence of shortcut keys of the graphics card, the following bloggers have not been realized
 * 4.Use single line comment: Ctrl + / blogger changed to alt+/
 * 5.Use multiline comments: Ctrl + shift + / blogger. This is not intended to be used
 * 6.Cancel multi line comments: Ctrl + shift + \ bloggers are not going to use this
 * 7.Copy the code of the specified line: Ctrl + (Alt +) down or Ctrl (+ Alt) + up
 * Change the way of Eclipse shortcut keys
 * 8.Delete the code of the specified line: ctrl+d
 * 9.Move up and down code: alt+up/down
 * 10.Insert a blank line above: ctrl + shift + enter
 * 11.How to view the source code: ctrl + mouse click or ctrl + shift + t
 * 12.Return to the previous edited page: alt + left
 * 13.Enter the next edit page: alt + right
 * 14.Select the specified class with the cursor to view the structure of the inheritance tree: ctrl + t
 * 15.Copy: ctrl + c
 * 16.Undo: ctrl + z
 * 17.Cancel undo: ctrl + y
 * 18.Cut: ctrl + x
 * 19.Paste: ctrl + v
 * 20.Save: ctrl + s
 * 21.Select all: ctrl + a
 * 22.Format code: ctrl + shitf + f cannot be used by bloggers
 * 23.Move selected rows backward as a whole: tab
 * 24.Move the selected rows forward as a whole: shift + tab
 * 25.In the current class, the structure of the class is displayed, and the search for specified methods and properties is supported: Ctrl+o
 * 26.Batch modify the specified variable name, method name, class name, etc.: alt+shift+r or ctrl + f
 * 27.Select the case switch of the structure to uppercase: ctrl + shift + x
 * 28.Select the case switch of the structure and change it to lowercase: ctrl + shift + y
 * 29.Call out and generate getter/setter / constructor and other structures: alt + shift + s
 * 30.Display the current resource attribute information: alt + enter
 * 31.Quick search: ctrl + k is a quick search
 * 
 * 32.Close the current window: ctrl+w
 * 32.Close all current windows: ctrl + shift + w
 * 33.View where the structure has been used: ctrl + shift + g
 * 34.Find and replace: ctrl + f
 * 35.Maximize the current View: ctrl + m
 * 36.Go directly to the first place of the current row: home
 * 37.Navigate directly to the end of the current row: end
 * 
 */
public class EclipseKeys {
	final double pi = 3.14;//This shows that it is a constant
public static void main(String[] args) {
	String s = new String();
	String str = new String();
	
	ArrayList list = new ArrayList();
	
	HashMap map = null;
	int map1 = 12;
	map1 = 18;
	
	Date date = new Date(123456);
}
}
class User
{
private int Id;	
private String name
public int getId() {
	return Id;
}
public void setId(int id) {
	Id = id;
}
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public User(int id, String name) {
	
	Id = id;
	this.name = name;
};


}

4. Review the difficulties of the Bank exercise

  • Customer information management software

5. Item 2: function demonstration

  • See video for details

6. Item 2: software structure design

7. Item 2: function introduction of CMUtility tool class

8. Item 2: Design of Customer class

9. Item 2: Design of CustomerList class

10. Project 2: Construction of the overall framework of CustomerView

11. Item 2: implementation of exit function of CustomerView

12. Project 2: implementation of customer list function of CustomerView

13. Project 2: implementation of CustomerView add customer function

14. Item 2: implementation of CustomerView modify customer function

15. Item 2: implementation of CustomerView delete customer function

16. Item II: summary

17. Understanding of inheritance

  • Students inherit human beings (the code is shown below)
  • Person.java
package com.atshangguigu.java;

public class Person {
	String name;
	int age;
	public Person()
	{
		
	}
	public Person(String name,int age)
	{
		this.name = name;
		this.age = age;
	}
	public void eat()
	{
		System.out.println("I can go to dinner in more than an hour");
	}
	public void sleep()
	{
		System.out.println("I slept until 2:30 this afternoon");
	}

}
  •  Student.java
package com.atshangguigu.java;
/*
 * A Person class has been defined. Here we can directly inherit the things in the Person class
 */
public class Student extends Person{//If we use extends Person here, we can directly inherit things from Person
	//String name;
	//int age;
	String major;
	public Student()
	{
		
	}
	public Student(String name,int age,String major)
	{
		this.name = name;
		this.age = age;
		this.major = major;
	}
	public void study()
	{
		System.out.println("Xiao Yang is studying hard Java ah!");
	}
	
}
  • ExtendTest.java
package com.atshangguigu.java;
/*
 * Object oriented feature 2: Inheritance
 * 1.Reduce code redundancy and improve code reusability
 * 2.Convenient for function expansion
 * 3.It provides the premise for the later use of polymorphism
*/
public class ExtendTest {
public static void main(String[] args) {
	Person p1 = new Person();
	p1.age = 1;
	p1.eat();
	
	Student s1 = new Student();
	s1.eat();
	s1.sleep();
	s1.name = "Yang";
	
}
}

18. Use of inheritance

  •  Person.java
package com.atshangguigu.java;

public class Person {
	String name;
	private int age;
	public Person()
	{
		
	}
	public Person(String name,int age)
	{
		this.name = name;
		this.age = age;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public void eat()
	{
		sleep();
		System.out.println("I can go to dinner in more than an hour");
	}
	private void sleep()
	{
		System.out.println("I slept until 2:30 this afternoon");
	}

}
  •  Student.java
package com.atshangguigu.java;
/*
 * A Person class has been defined. Here we can directly inherit the things in the Person class
 */
public class Student extends Person{//If we use extends Person here, we can directly inherit things from Person
	//String name;
	//int age;
	String major;
	public Student()
	{
		
	}
	public Student(String name,int age,String major)
	{
		this.name = name;
		setAge(age);
		this.major = major;
	}
	public void study()
	{
		System.out.println("Xiao Yang is studying hard Java ah!");
	}
	public void show()
	{
		System.out.println("name:" + name + ",age:" + getAge());
	}
}

  • ExtendTest.java
package com.atshangguigu.java;
/*
 * Object oriented feature 2: Inheritance  
 * 1, Inherited benefits
 * 1.Reduce code redundancy and improve code reusability
 * 2.Convenient for function expansion
 * 3.It provides the premise for the later use of polymorphism
 * 
 * 2, Inherited format: Class A extensions B {}
 * 	A: Subclass, derived class, subclass
 *  B: Parent class, superclass, base class, superclass
 *  2.1 Embodiment: once subclass A inherits the structure declared in parent class B: attributes and methods (private inherited to, but hidden - invisible gene)
 *  In particular, for a property or method declared private in the parent class, after the child class inherits the parent class, it is still considered to have obtained the private structure in the parent class
 *  Only because of the influence of encapsulation, subclasses cannot directly call the structure of the parent class. Encapsulation and inheritance are complementary and conflict, and they call their own
 *  2.2 After the subclass inherits the parent class, it can also declare its own unique properties and methods: to realize the expansion of functions
 *  The relationship between subclasses and parent classes, and the relationship between different subsets and collections
 */
public class ExtendTest {
public static void main(String[] args) {
	Person p1 = new Person();
	//p1.age = 1;
	p1.eat();
	
	Student s1 = new Student();
	s1.eat();
	//s1.sleep();
	s1.name = "Yang";
	s1.setAge(10);
	System.out.println(s1.getAge());
	
}
}

19. Redefinition of inheritance

 * 3, Some provisions on inheritance in java

         1. A class can be inherited by multiple subclasses. (a person can have multiple children)
         2. Single inheritance in Java: a class can only have one parent class. (Lv Bu: do you scold again?) [there can be multiple parent classes in C + +]
         3. Paternity is a relative concept. Multi-layer inheritance (grandfather grandfather father son: four generations together - from the perspective of gene)
         4. The parent class directly inherited by the child class is called the direct parent class, and the parent class indirectly inherited is called the indirect parent class
         5. After the subclass inherits the father, it directly obtains all the declared properties and methods in the parent class and indirect parent class

20. Understanding of object class

  • Create a class, and then directly call the unknown inheritance parent class ("who's my father?")
  • Creature s = new Creature(); s. ----- you can know that the corresponding function is generated later
  • IV
    1. If we do not explicitly declare the father of a class, we will directly inherit the java.lang.Object class
    2. All Java classes (except java.lang.Object class) are directly or indirectly inherited from java.lang.Object class
    3. It means that all Java classes have the function declared by java.lang.Object class

20. Daily test

21. Inheritance exercise 1: basic operation

  • Arrow: subclass points to parent

package day12;
/*
(1)Define a ManKind class, including
Member variables int sex and int salary;
    Method void manOrWoman(): displays "man" (sex==1) or "woman" (sex==0) according to the value of sex;
Method void employed(): displays "no job" (salary==0) or "job" (salary!=0) according to the value of salary.
 */
public class ManKind {
	//attribute
	private int sex;
	private int salary;
	
	//constructor 
	public ManKind() {
		
	}
	
	public ManKind(int sex, int salary) {
		super();
		this.sex = sex;
		this.salary = salary;
	}

	//method
	void manOrWoman()
	{
		if(sex == 1)
		{
			System.out.println("man");
		}
		else if(sex == 0)
		{
			System.out.println("woman");
		}
		else
		{
			System.out.println("neutral");
		}
			
	}
	
	void employeed()
	{
		String job = ((salary == 0)?"no job":"job");
		System.out.println(job);
	}
	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;
	}
	
}
package day12;
/*
(2)Define the class Kids, inherit ManKind, and include
Member variable int yearold; 
    The printAge() method prints the value of yearold.
 *///   Here, the conditions of javabean are: 1. The class is public; 2. No parameter constructor; 3. Private properties (get and set methods)
   //   [mentioned later in the reflection process]
public class Kid extends ManKind{
	//attribute
	private int yearsOld;
	
	//constructor 
	public Kid() {
	
	}
	public Kid(int yearsOld) {
	
		this.yearsOld = yearsOld;
	}

	//method
	public void printAge()
	{
		System.out.println("I am " + yearsOld + "years old ");
	}
	public int getYearsOld() {
		return yearsOld;
	}

	public void setYearsOld(int yearsOld) {
		this.yearsOld = yearsOld;
	}
	
}
package day12;
/* 
(3)Define the class KidsTest, instantiate the object someKid of Kids in the main method of the class, and access it with this object
     Member variables and methods of its parent class.
 */
public class KidTest {
public static void main(String[] args) {
	Kid somekid = new Kid(12);
	
	somekid.printAge();
	
	somekid.setSex(0);
	somekid.setSalary(18);
	somekid.manOrWoman();
	somekid.employeed();
}
}

22. Inheritance exercise 2: basic operation

  •   The following is written by the blogger according to his own understanding, which may be different from the video
package com.atshangguigu.exer;
/*
 * 
 */
public class Circle {
	private double radius;//radius
	public Circle()
	{
		radius = 1.0;
	}
	public double getRadius() {
		return radius;
	}
	public void setRadius(double radius) {
		this.radius = radius;
	}
	//Returns the radius of a circle
	public double findArea()
	{
		return Math.PI * getRadius() * getRadius();
	}
}

package com.atshangguigu.exer;

public class Cylinder extends Circle{
	private double length;
	Cylinder()
	{
		length = 1.0;
	}
	public double getLength() {
		return length;
	}
	public void setLength(double length) {
		this.length = length;
	}
	double findVolumn()
	{
		return getLength()*findArea();
	}
}
package com.atshangguigu.exer;

public class FinalTest {
public static void main(String[] args) {
	Cylinder test = new Cylinder();
	System.out.println(test.findVolumn());
	
	test.setRadius(58.2);
	test.setLength(12);
	System.out.println(test.findVolumn());
}
}

23. Use of eclipse debug

  • It will be used more in actual development
  • How to debug a program:
    1. System.out.println().
    2. Eclipse - Debug debugging
  • Method of adding breakpoints: double click (breakpoints can be understood as small levels, and we can set multiple breakpoints in the program) -- right click (click debug as): the little bug interface is displayed

  • The corresponding interface is as follows:

  • Drop to frame: the position of the first line is reached  

24. Debug debugging is used in project 2

25. Solve the problem of step into function failure in Debug

  • Did not enter the method: the reason is debug configurations --- JRE (jdk1.8.0) - > see the video for the specific process

26. Understanding of method rewriting

package com.atshangguigu.exer1;

public class Person {
	String name;
	int age;
	
	public Person()
	{}
	public Person(String name,int age)
	{
		this.name = name;
		this.age = age;
	}
	
	public void eat()
	{
		System.out.println("having dinner");
	}
	public void walk(int distance)
	{
		System.out.println("I left today" + distance + "kilometre");
	}
}
package com.atshangguigu.exer1;

public class Student extends Person {
	String major;
	public Student()
	{}
	public Student(String major)
	{
		this.major = major;
	}
	public void study()
	{
		System.out.println("I love Tianjin");
	}
	public void eat()
	{
		System.out.println("Students eat two portions of rice at a meal,Because there is too little rice in the school five canteen");
	}
}
package com.atshangguigu.exer1;
/*
 * Method override:
 * 1.Override: after a subclass inherits the parent class, it can override the methods with the same name and parameters in the parent class
 * 2.Application: after rewriting, when a subclass object is created and a method with the same name and parameter as the parent class is called through the subclass object, the method of overriding the parent class by the subclass is actually called
 */
public class StudentTest {
public static void main(String[] args) {
	Student s = new Student("Instrument Engineering");
	s.eat();
	s.walk(18);
	
	s.study();
}
}
  • Interview question: overloading and rewriting of distinguishing methods

27. Details of method rewriting

  • Person.java
package com.atshangguigu.exer1;

public class Person {
	String name;
	int age;
	
	public Person()
	{}
	public Person(String name,int age)
	{
		this.name = name;
		this.age = age;
	}
	//Override it
	public void eat()
	{
		System.out.println("having dinner");
	}
	public void walk(int distance)
	{
		System.out.println("I left today" + distance + "kilometre");
		eat();
		show();
	}
	private void show()//Private method
	{
		System.out.println("I'm not a good man");
	}
	
	public Object info()
	{
		return null;
	}
	
	public double info1()
	{
		return 10.0;
	}
}
  • Student.java
package com.atshangguigu.exer1;

public class Student extends Person {
	String major;
	public Student()
	{}
	public Student(String major)
	{
		this.major = major;
	}
	public void study()
	{
		System.out.println("I love Tianjin");
	}
	public void eat()
	{
		System.out.println("Students eat two portions of rice at a meal,Because there is too little rice in the school five canteen");
	}
	//It cannot be rewritten here, because you can see that there is no green triangle in front of here, indicating that there is no rewriting
    public void show()//Private method
	 
	{
		System.out.println("I am a good student");
	}
	
    public String info()//The meaning here is that we change the Object in the parent class to String
	{
		return null;
	}
    /*int And double are juxtaposed
    public int info1()
	{
		return 10.0;
	}
	*/
}
  • StudentTest.java
package com.atshangguigu.exer1;
/*
 * Method override:
 * 1.Override: after a subclass inherits the parent class, it can override the methods with the same name and parameters in the parent class
 * 2.Application: after rewriting, when a subclass object is created and a method with the same name and parameter of the parent class is called through the subclass object,
 *   What is actually called is the method of the child class overriding the parent class
 * 3.Provisions for rewriting:
 * 	 Method declaration: permission modifier return value type method name (formal parameter list)
 *             {
 *             Method body
 *             }
 *             It is a convention that the method in the subclass is called overridden, and the method in the parent class is called overridden
 *      1.The method name and parameter list of the method overridden by the subclass are the same as those of the method overridden by the parent class
 *      2.The permission modifier of the method overridden by the subclass is not less than the permission modifier in the parent class
 *        Special case: the subclass cannot override the private method in the parent class
 *      3.Return value type:
 *        If the return value of the method overridden by the parent class is void, the return value type of the method overridden by the child class can only be void
 *        If the return value type of the method overridden by the parent class is type A, the return value type of the subclass overriding method can be class A or subclass of class A
 *        If the return value type of the method overridden by the parent class is the basic data type, the return value type of the subclass re method must also be the same
 *      4.The exception type thrown by the method overridden by the subclass shall not be greater than the exception type thrown by the overridden parent class
 *             Permission modifier returns the type of value type method name (formal parameter list) throws exception
 *             {
 *             Method body
 *             }
 *        Parent class: Object --- Exception 
 *        The subclass is: String --- the exception is Runtime Exception
 *        [This part will be described in the exception handling section]
 *      5.We usually paste the specific development method directly, so it is absolutely not wrong. ------ human wisdom is to be lazy
 *      6.Shortcut keys for rewriting, using Alt + /
 * *-*-*-*-***-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
 *  	Methods with the same name and parameters in the subclass and parent class are either declared non static (consider overriding) or static (this is not called overriding)     
 */
public class StudentTest {
public static void main(String[] args) {
	Student s = new Student("Instrument Engineering");
	s.eat();
	s.walk(18);//This sentence proves that a subclass cannot override the method of price in the parent class
	
	s.study();
	
}
}

28. Practice of method rewriting

  •   The second question above is very simple. The code here will not be pasted repeatedly. The amount of code is relatively large and meaningless

29. Different permission modifications in test 4

 

  • As shown above, you can directly change the inherited parent class of the new class in Browse  
  • Under java2
package com.atshangguigu.java2;
/*
 * Experience four different authority modifications
 */
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;
	}
}

  • SubOrder.java under java3
package com.atshangguigu.java3;
import com.atshangguigu.java2.Order;
public class SubOrder extends Order {
	public void method()
	{
		orderProtected = 1;
		orderPublic = 2;
		
		methodProtected();
		methodPublic();
		/*In subclasses of different packages, properties and methods declared as private and default permissions in the Order class cannot be called
		orderDefault = 3;
		orderPrivate = 4;
		methodDefault();
		methodPrivate();
		*/
	}
	
}
  • OrderTest.java under java3
package com.atshangguigu.java3;

import com.atshangguigu.java2.Order;//ctrl + shift + o is a process of guiding packets

public class OrderTest {
public static void main(String[] args) {
	Order order = new Order();
	//If ordinary classes under different packages want to call the properties and methods in Order, they can only call the public class, and the other private protected by default cannot be called
	//order.orderPrivate = 1;
//	order.orderDefault = 2;
//	order.orderProtected = 3;
	order.orderPublic = 4;
	
	
//	order.methodDefault();
//	order.methodProtected();
	order.methodPublic();
	
}
}

30.super calling properties and methods -- super love bean's smile

  • Properties are not overridden, and there are methods
  • Barrage: super is the father of this
  • Person.java
package com.atshangguigu.java4;

public class Person {
	String name;
	int age;
	int id = 1;//ID number
	public Person()
	{
		
	}
	public Person(String name)
	{
		this.name = name;
	}
	public Person(String name,int age)
	{
		this(name);
		this.age = age;
	}
	
	public void eat()
	{
		System.out.println("We're going to dinner in an hour");
	}
	public void walk()
	{
		System.out.println("Born to run");
	}
}
  • student.java
package com.atshangguigu.java4;

public class Student extends Person{
	String major;
	int id = 20212023;//Student number
	public Student()
	{}
	public Student(String major)
	{
		this.major = major;
	}
	@Override
	public void eat()
	{
		super.eat();
		System.out.println("Today, I went to the fourth canteen to eat rice,Or go to the school five canteen to eat spicy hot?");
	}
	public void study()
	{
		System.out.println("There is a laser measurement technology class this evening");
	}
	public void show()
	{
		System.out.println("name = " + super.name + ",age = " + this.age);
		System.out.println("The student number is" + id);
		System.out.println("The ID number is" + super.id);
	}
	
}

  • SuperTest.java
package com.atshangguigu.java4;
/*
 * super Use of keywords
 * 1.super Can be understood as the parent class
 * 2.super Can be used to call property method constructors
 * 3.super Use of
 * 	3.1 We can explicitly call the declared properties or methods in the parent class by using "super. Attribute" or "super. Method" in the method or constructor of the child class
 *     But usually, we are used to omitting "super"
 *  3.2 Special case: when the properties of the same name are defined in the child class and the parent class, we want to call the declarative properties in the parent class in the subclass, and we must explicitly use the "super. attribute" method.
 *     The declaration in the parent class is called
 *  3.3 Special case: when a child rewrites the method in the parent class, we want to call the rewritten method in the parent class when we call it in the subclass. We must use the super. method explicitly.
 *     The declaration in the parent class is called
 */
public class SuperTest {
public static void main(String[] args) {
	Student stu = new Student();
	stu.show();
	stu.study();
	stu.eat();
}
}

31.super call constructor

  • Person.java
package com.atshangguigu.java4;

public class Person {
	String name;
	int age;
	int id = 1;//ID number
	public Person()
	{
		System.out.println("I'm pig eight");
	}
	public Person(String name)
	{
		this.name = name;
	}
	public Person(String name,int age)
	{
		this(name);
		this.age = age;
	}
	
	public void eat()
	{
		System.out.println("We're going to dinner in an hour");
	}
	public void walk()
	{
		System.out.println("Born to run");
	}
}
  • Student.java
package com.atshangguigu.java4;

public class Student extends Person{
	String major;
	int id = 20212023;//Student number
	public Student()
	{
		
	}
	public Student(String major)
	{
		this.major = major;
	}
	public Student(String name,int age,String major)
	{
		super(name,age);
		this.major = major;
	}
	@Override
	public void eat()
	{
		super.eat();
		System.out.println("Today, I went to the fourth canteen to eat rice,Or go to the school five canteen to eat spicy hot?");
	}
	public void study()
	{
		System.out.println("There is a laser measurement technology class this evening");
	}
	public void show()
	{
		System.out.println("name = " + this.name + ",age = " + this.age);
		System.out.println("The student number is" + id);
		System.out.println("The ID number is" + super.id);
	}
	
}
  • SuperTest.java
package com.atshangguigu.java4;
/*
 * super Use of keywords
 * 1.super Can be understood as the parent class
 * 2.super Can be used to call property method constructors
 * 3.super Use of
 * 	3.1 We can explicitly call the declared properties or methods in the parent class by using "super. Attribute" or "super. Method" in the method or constructor of the child class
 *     But usually, we are used to omitting "super"
 *  3.2 Special case: when the properties of the same name are defined in the child class and the parent class, we want to call the declarative properties in the parent class in the subclass, and we must explicitly use the "super. attribute" method.
 *     The declaration in the parent class is called
 *  3.3 Special case: when a child rewrites the method in the parent class, we want to call the rewritten method in the parent class when we call it in the subclass. We must use the super. method explicitly.
 *     The declaration in the parent class is called
 * 4.super Invoking Constructors 
 *  4.1 We can explicitly use the "super (formal parameter list)" method in the constructor of the subclass to call the specified constructor declared in the parent class
 *  4.2"super(The use of formal parameter list must be declared in the first line of subclass constructor
 *  4.3 In the class constructor, we can only choose one of "this" or "super" and cannot appear at the same time
 *  4.4 In the first line of the constructor, if there is no explicit declaration of "this (formal parameter list)" or "super (formal parameter list)", the null parameter constructor super() in the parent class is called by default;
 *  4.5 Among multiple constructors of a class, at least one class constructor uses "super (formal parameter list)" to call the constructor of the parent class
 */
public class SuperTest {
public static void main(String[] args) {
	Student stu = new Student();
	stu.show();
	stu.study();
	stu.eat();
	
	Student s1 = new Student("Yang",23,"Instrument Engineering!");
	s1.show();
	System.out.println("*-*-*-*--*-*-*-*-*-*--*-*-*-*-*-");
	Student s2 = new Student();
}
}

32. The whole process of subclass object instantiation

  •  * The whole process of subclass object instantiation
     * 1. From the result: (inheritance)
     *        After the subclass inherits from the parent class, it obtains the properties and methods declared in the parent class
     *        When a subclass object is created, the declared properties in all parent classes will be loaded in heap space
     * 2. From the perspective of process:
     *          When we create an object through the constructor of a subclass, we must call the constructor of the parent class directly or indirectly,
     *          Then call the constructor of the parent class of the parent class. Because all the structures of the parent class have been loaded, you can see that there are in memory
     *          The structure of the parent class, the subclass object can be called
     *  Explicit: Although the constructor of the parent class is called when creating a subclass object, only one object, that is, the new object, has been created               Come out of the object

33. After class exercises of inheritance and super

  • Account.java
package com.atshangguigu.java6;
/*
 	1,Write a class named Account to simulate an Account. The properties and methods of this class are shown in the figure below. This class includes the following properties:
Account id, balance, annual interest rate, annualInterestRate; methods included: accessor methods (getter and
setter Method), return the monthly interest rate method getMonthlyInterest(), withdrawal method withdraw(), deposit method
deposit(). 
 */
public class Account {
	private int id;//account number
	private double balance;//deposit
	private double annualInterestRate;//Annual interest rate
	
	//constructor 
	
	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;
	}
	//Monthly interest rate
	public double getMonthlyInterest()
	{
		return annualInterestRate / 12;
	}
	//Withdraw money
	public void withdraw (double amount)
	{
		if (balance >= amount)
		{
			balance -= amount;
			return ;
		}
		else{
			System.out.println("Sorry, your credit is running low,No money");
			return ;
		}
	}
	//save money
	public void deposit (double amount)
	{
		balance += amount;
	}
}
  • AccountTest.java
package com.atshangguigu.java6;
/*
         Write a user program to test the Account class.
         1.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%.
         2.Withdraw 30000 yuan by withdraw method and print the balance.
		 3.Then withdraw 2500 yuan by withdraw method, deposit 3000 yuan by deposit method, and then print the balance and monthly interest rate.
 * 
 */
public class AccountTest {
public static void main(String[] args) {
	Account test = new Account(1122,20000,0.045);
	test.withdraw(30000);
	System.out.println("Your account balance is" + test.getBalance());
	test.withdraw(2500);
	test.deposit(3000);
	System.out.println("Your account balance is" + test.getBalance() + "  The monthly interest rate of the current account is" + 100*test.getMonthlyInterest() + "%");
}
}
  • CheckAccount.java
package com.atshangguigu.java6;
/*
	2,Create a subclass of the Account class. CheckAccount represents an overdrawable Account, and an attribute is defined in the Account
overdraft Represents the overdraft limit. Override the withdraw method in the CheckAccount class, and its algorithm is as follows:
	If (withdrawal amount < account balance),
	Direct withdrawal
	If (withdrawal amount > account balance),
	Calculate the amount of overdraft required
	Judge whether the overdraft amount is sufficient to cover the overdraft needs. If yes
	Modify the account balance to 0 to offset the overdraft amount
	If not
	Prompt the user to exceed the limit of transparent amount
 */
public class CheckAccount extends Account{
	private double overdraft;//Overdraft limit
	public CheckAccount(int id, double balance, double annualInterestRate,double overdraft)
	{
		super(id,balance,annualInterestRate);
		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 )
		{	//Mode 1
			//setBalance(getBalance() - amount);
			//Mode II
			super.withdraw(amount);
		}
		else if(overdraft >= (amount - getBalance()))//The overdraft limit plus the balance is sufficient
		{
			overdraft -= (amount - getBalance());
			setBalance(0);
			//Or
			super.withdraw(getBalance());
		}
		else
		{
			System.out.println("Exceed the overdraft limit");
		}
	}

}
  • CheckAccountTest.java
package com.atshangguigu.java6;
/*
	Requirements: write a user program to test the CheckAccount class. In the user program, create an account of 1122 and more
 The amount is 20000, the annual interest rate is 4.5%, and the overdraft limit is 5000 yuan.
Withdraw 5000 yuan by withdraw method, and print the account balance and transparent amount.
Then withdraw 18000 yuan by withdraw method, and print the account balance and transparent amount.
Then withdraw 3000 yuan by withdraw method, and print the account balance and transparent amount.
 */
public class CheckAccountTest {
public static void main(String[] args) {
	CheckAccount acc = new CheckAccount(1122,20000,0.045,5000);
	acc.withdraw(5000);
	System.out.println("Your account balance is:" + acc.getBalance());
	System.out.println("Your overdraft limit is:" + acc.getOverdraft());
	acc.withdraw(18000);
	System.out.println("Your account balance is:" + acc.getBalance());
	System.out.println("Your overdraft limit is:" + acc.getOverdraft());
	acc.withdraw(3000);
	System.out.println("Your account balance is:" + acc.getBalance());
	System.out.println("Your overdraft limit is:" + acc.getOverdraft());
}
}

34. The use of polymorphism ---- more difficult, more important (teacher's original words) (Polymorphism)

  • Person.java
package com.atshangguigu.java7;

public class Person {
	String name;
	int age;
	
	public void eat()
	{
		System.out.println("Born a pig,I can eat very well");
	}
	public void walk()
	{
		System.out.println("Have you seen a pig run");
	}
	
}
  • Man.java
package com.atshangguigu.java7;

public class Man extends Person{
	boolean isMoking;
	public void earnMoney()
	{
		System.out.println("earn money,take as a wife");
	}
	public void eat()
	{
		System.out.println("Eat more");
	}
	public void walk()
	{
		System.out.println("Delete Library,make off with money");
	}
    public void isSmoking()
   {
    system.out.println("Boys can smoke");
   }
}
  • Woman.java
package com.atshangguigu.java7;

public class Woman extends Person{
	boolean isBeauty;
	public void goShopping()
	{
		System.out.println("Girls like shopping");
	}
	public void eat()
	{
		System.out.println("Don't eat");
	}
	public void walk()
	{
		System.out.println("walk");
	}
}
  • PersonTest.java
package com.atshangguigu.java7;
/*
 * Object oriented feature 3: polymorphism
 * 
 * 1.Understanding polymorphism: it can be understood as multiple forms of a thing
 * 2.What is polymorphism: the reference of the parent class points to the object of the child class (the object of the child class points to the reference of the parent class)
 * 3.The use of polymorphism: the use of virtual methods
 * 		With the polymorphism of objects, we can only call the methods declared in the parent class when compiling, but when running, we actually
 * What is called is the method of the subclass overriding the parent class
 * Summary: compile to the left, run to the right ------ find commonalities
 * 4.Premise of polymorphism:
 * (1)There should be class inheritance
 * (2)There should be method rewriting
 * 
 * 
 */
public class PersonTest {
public static void main(String[] args) {
	Person p1 = new Person();
	p1.eat();
	
	Man man = new Man();
	man.eat();
	man.age = 23;
	man.earnMoney();
	//*-*-*--*-*-*-*-*-*--*--*-*-*--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
	//This is polymorphism
	//Object polymorphism: the reference of the parent class points to the object of the child class
	
	Person p2 = new Man();
	//Use of polymorphism: when calling a method with the same name and parameter as the child parent class, the actual execution is the method of the child class overriding the parent class - virtual method call (don't delve into it here)
	p2.eat();//What is called here is the method of the subclass
	p2.walk();
	//Image metaphor: suppose you call a secretary, the Secretary finds someone, and then goes out to dinner together (men and women don't eat the same amount)
	
	//p2.earnMoney(); / / look at the left when compiling and the right when running (barrage: compile to the left and run to the right)
	
	
	
}
}

35. Examples of polymorphism use

package com.atshangguigu.java7;

import java.sql.Connection;

public class AnminalTest {
	public static void main(String[] args) {
		AnminalTest test = new AnminalTest();
		test.func(new Ribbit());
		test.func(new Cat());
	}
	public void func(Anminal anminal)
	{
		anminal.eat();
		anminal.shout();
	}
	//If there is no polymorphism, we will rewrite the following code
	//We have to create a lot of overloaded methods
	public void func(Ribbit anminal)
	{
		anminal.eat();
		anminal.shout();
	}
	public void func(Cat anminal)
	{
		anminal.eat();
		anminal.shout();
	}
	
}
class Anminal
{
	public void eat()
	{
		System.out.println("animal:Just rice");
	}
	public void shout()
	{
		System.out.println("animal:call");
	}
}
class Ribbit extends Anminal
{
	public void eat()
	{
		System.out.println("Little white rabbit:Qia radish");
	}
	public void shout()
	{
		System.out.println("Little white rabbit:Woof, woof(I don't know what to call it)");
	}
}
class Cat extends Anminal
{
	public void eat()
	{
		System.out.println("Little black cat: eat small fish");
	}
	public void shout()
	{
		System.out.println("Little black cat: meow meow meow");
	}
}

//Example 2:
class Order
{
	public void method(Object obj)
	{
		
	}
}
//Example 3:
class Driver
{
	public void doData(Connection conn)//Connection is a parent class structure. What is actually passed is the object of the child class
	{
		//conn = new MySQLConnection();
		//Steps for operating specifications
//		conn.method1();
//		conn.method2();
		
	}
}

36. Polymorphism does not apply to attributes

  1. Define an id = 1001 in Person;
  2. Define an id = 1002 in the Student;
  3. By using Person p = new Student();
  4. The result of calling print p.id is 1001
  • Object polymorphism only applies to methods, not attributes

37. Re understanding of virtual method calls

  • A method with the same name and parameters as the parent class is defined in the subclass. In the case of polymorphism, the method of the parent class at this time is called a virtual method (it feels that the parent class is relatively virtual because it is called a virtual method). The parent class dynamically calls the method belonging to the subclass according to the different subclass objects assigned to it. Such method calls cannot be determined at compile time and are only known at run time.
  • Interview question: is polymorphism a compile time behavior or a run-time behavior? (detailed explanation is as follows)
package com.atshangguigu.java3;

import java.util.Random;

//Interview question: is polymorphism a compile time behavior or a runtime behavior?
//The certificate is as follows:
class Animal  {
 
	protected void eat() {
		System.out.println("animal eat food");
	}
}

class Cat  extends Animal  {
 
	protected void eat() {
		System.out.println("cat eat fish");
	}
}

class Dog  extends Animal  {
 
	public void eat() {
		System.out.println("Dog eat bone");

	}

}

class Sheep  extends Animal  {
 

	public void eat() {
		System.out.println("Sheep eat grass");

	}

 
}

public class InterviewTest {

	public static Animal  getInstance(int key) {
		switch (key) {
		case 0:
			return new Cat ();
		case 1:
			return new Dog ();
		default:
			return new Sheep ();
		}

	}

	public static void main(String[] args) {
		int key = new Random().nextInt(3);

		System.out.println(key);

		Animal  animal = getInstance(key);
		
		animal.eat();
		 
	}

}
  • To explain the above code is to randomly generate a random number corresponding to different animals, and each animal has different ways. -- the running process is called dynamic binding

  • You should pay attention to the overloading and writing of this method, which may be asked during the interview

38. Daily test

First write the code, and then take your time to understand

  • What is polymorphism? What is a virtual method call?

      Object polymorphism: the reference of the parent class points to the object of the child class.

Person p = new Man();

p.eat();

When calling a method, look at the left when compiling and the right when running.

  • How many direct parent classes can a class have? (only one)
  • How many subclasses can a parent class have? (multiple)
  • Can a subclass get the structure in the parent of the direct parent? (yes) A is B---true? Decide to inherit
  • Can a subclass get the property or method of private permission in the parent class? (yes)
  • What are the specific rules for method override / overwrite?

The method name and formal parameter list are the same

Permission modifier

Return value

Exception thrown

  • What are the specific points for attention when super calls the constructor (put it in the first line, and you must choose one of the two or use the default constructor)

         This (formal parameter list): other constructors overloaded by this class

         Super (formal parameter list): call the constructor specified in the parent class

        n n – 1 1  

39. Use of downward transformation

  • Add in the previous PersonTest.java
	//p2.earnMoney();// When compiling, you look at the left and when running, you look at the right (barrage: compiling to the left and running to the right)
	//It is not possible to call the method properties specific to subclasses. p2 is the type of Person when compiling
	//p2.earnMoney();
	p2.name = "Yang";
	//p2.isSmoking = true;
	//Whether the special attributes in man have been declared in memory. Since we have re declared a Person type, we can't call it
	//After the polymorphism of the object, the specific attributes and methods in the subclass are actually loaded in memory, but because the variable is declared as the parent object type
	//When compiling, you can only call the properties and methods of the parent class, but the properties and methods of the child class cannot be used
	
	//How to call properties and methods unique to subclasses--- Use cast
	//Downward transformation --- forced type conversion upward transformation --- automatic type conversion (polymorphic)
	
	Man m1 = (Man) p2;
	m1.earnMoney();
	m1.isSmoking();
	//When casting is used, an exception of ClassCastException may occur
//For example, the following code
//Woman w1 = (Woman)p2;
//w1.goShopping();
//instanceof: use of

40. Use of instanceof keyword

  • The following is the code of PersonTest.java
package com.atshangguigu.java;
/*
 * Object oriented feature 3: polymorphism
 * 
 * 1.Understanding polymorphism: it can be understood as multiple forms of a thing
 * 2.What is polymorphism: the reference of the parent class points to the object of the child class (the object of the child class points to the reference of the parent class)
 * 3.The use of polymorphism: the use of virtual methods
 * 		With the polymorphism of objects, we can only call the methods declared in the parent class when compiling, but when running, we actually
 * What is called is the method of the subclass overriding the parent class
 * Summary: compile to the left, run to the right ------ find commonalities
 * 4.Premise of polymorphism:
 * (1)There should be class inheritance
 * (2)There should be method rewriting
 * 5.The polymorphism of objects is only applicable to methods, not attributes (both compilation and operation are based on the left)
 * 
 * 
 */
public class PersonTest {
public static void main(String[] args) {
	Person p1 = new Person();
	p1.eat();
	
	Man man = new Man();
	man.eat();
	man.age = 23;
	man.earnMoney();
	//*-*-*--*-*-*-*-*-*--*--*-*-*--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
	//This is polymorphism
	//Object polymorphism: the reference of the parent class points to the object of the child class
	
	Person p2 = new Man();
	//Use of polymorphism: when calling a method with the same name and parameter as the child parent class, the actual execution is the method of the child class overriding the parent class - virtual method call (don't delve into it here)
	p2.eat();//What is called here is the method of the subclass
	p2.walk();
	//Image metaphor: suppose you call a secretary, the Secretary finds someone, and then goes out to dinner together (men and women don't eat the same amount)
	
	//p2.earnMoney();//When compiling, you look at the left and when running, you look at the right (barrage: compiling to the left and running to the right)
	//It is not possible to call the method properties specific to subclasses. p2 is the type of Person when compiling
	//p2.earnMoney();
	p2.name = "Yang";
	//p2.isSmoking = true;
	//Whether the special attributes in man have been declared in memory. Since we have re declared a Person type, we can't call it
	//After the polymorphism of the object, the specific attributes and methods in the subclass are actually loaded in memory, but because the variable is declared as the parent object type
	//When compiling, you can only call the properties and methods of the parent class, but the properties and methods of the child class cannot be used
	
	//How to call properties and methods unique to subclasses--- Use cast
	//Downward transformation --- forced type conversion upward transformation --- automatic type conversion (polymorphic)
	
	Man m1 = (Man) p2;
	m1.earnMoney();
	m1.isSmoking();
	//When casting is used, an exception of ClassCastException may occur
	//For example, the following code
	//Woman w1 = (Woman)p2;
	//w1.goShopping();
	/*instanceof Use of keywords
	 * 
	 * a instanceof A:Judge whether object a is an instance of class A. if so, return true; otherwise, return false
	 * 
	 * Usage: in order to avoid the exception of ClassCastException during downward transformation, we need to do it before downward transformation
	 * instanceof If it returns true, it will be transformed downward. If it returns false, it will not be transformed downward
	 * 
	 * If a instanceof A returns true and a instanceof B is also true, then B is the parent class of A
	 */
	if(p2 instanceof Woman)
	{
		Woman w1 = (Woman)p2;
		w1.goShopping();
		System.out.println("p2 It's a Woman");
	}
	else
	{
		System.out.println("p2 Not a Woman");
	}
	if(p2 instanceof Man)
	{
		System.out.println("p2 yes Man");
	}
	else
	{
		System.out.println("p2 no Man");
	}
	if(p2 instanceof Person)
	{
		System.out.println("p2 yes Person");
	}
	else
	{
		System.out.println("p2 no Person");
	}
	if(p2 instanceof Object)
	{
		System.out.println(" Yes ");
	}
	else
	{
		System.out.println("No");
	}
}
}

41. Several common problems of downward transformation

package com.atshangguigu.java;
/*
 * Object oriented feature 3: polymorphism
 * 
 * 1.Understanding polymorphism: it can be understood as multiple forms of a thing
 * 2.What is polymorphism: the reference of the parent class points to the object of the child class (the object of the child class points to the reference of the parent class)
 * 3.The use of polymorphism: the use of virtual methods
 * 		With the polymorphism of objects, we can only call the methods declared in the parent class when compiling, but when running, we actually
 * What is called is the method of the subclass overriding the parent class
 * Summary: compile to the left, run to the right ------ find commonalities
 * 4.Premise of polymorphism:
 * (1)There should be class inheritance
 * (2)There should be method rewriting
 * 5.The polymorphism of objects is only applicable to methods, not attributes (both compilation and operation are based on the left)
 * 
 * 
 */
public class PersonTest {
public static void main(String[] args) {
	Person p1 = new Person();
	p1.eat();
	
	Man man = new Man();
	man.eat();
	man.age = 23;
	man.earnMoney();
	//*-*-*--*-*-*-*-*-*--*--*-*-*--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
	//This is polymorphism
	//Object polymorphism: the reference of the parent class points to the object of the child class
	
	Person p2 = new Man();
	//Use of polymorphism: when calling a method with the same name and parameter as the child parent class, the actual execution is the method of the child class overriding the parent class - virtual method call (don't delve into it here)
	p2.eat();//What is called here is the method of the subclass
	p2.walk();
	//Image metaphor: suppose you call a secretary, the Secretary finds someone, and then goes out to dinner together (men and women don't eat the same amount)
	
	//p2.earnMoney();//When compiling, you look at the left and when running, you look at the right (barrage: compiling to the left and running to the right)
	//It is not possible to call the method properties specific to subclasses. p2 is the type of Person when compiling
	//p2.earnMoney();
	p2.name = "Yang";
	//p2.isSmoking = true;
	//Whether the special attributes in man have been declared in memory. Since we have re declared a Person type, we can't call it
	//After the polymorphism of the object, the specific attributes and methods in the subclass are actually loaded in memory, but because the variable is declared as the parent object type
	//When compiling, you can only call the properties and methods of the parent class, but the properties and methods of the child class cannot be used
	
	//How to call properties and methods unique to subclasses--- Use cast
	//Downward transformation --- forced type conversion upward transformation --- automatic type conversion (polymorphic)
	
	Man m1 = (Man) p2;
	m1.earnMoney();
	m1.isSmoking();
	//When casting is used, an exception of ClassCastException may occur
	//For example, the following code
	//Woman w1 = (Woman)p2;
	//w1.goShopping();
	/*instanceof Use of keywords
	 * 
	 * a instanceof A:Judge whether object a is an instance of class A. if so, return true; otherwise, return false
	 * 
	 * Usage: in order to avoid the exception of ClassCastException during downward transformation, we need to do it before downward transformation
	 * instanceof If it returns true, it will be transformed downward. If it returns false, it will not be transformed downward
	 * 
	 * If a instanceof A returns true and a instanceof B is also true, then B is the parent class of A
	 */
	if(p2 instanceof Woman)
	{
		Woman w1 = (Woman)p2;
		w1.goShopping();
		System.out.println("p2 It's a Woman");
	}
	else
	{
		System.out.println("p2 Not a Woman");
	}
	if(p2 instanceof Man)
	{
		System.out.println("p2 yes Man");
	}
	else
	{
		System.out.println("p2 no Man");
	}
	if(p2 instanceof Person)
	{
		System.out.println("p2 yes Person");
	}
	else
	{
		System.out.println("p2 no Person");
	}
	if(p2 instanceof Object)
	{
		System.out.println(" Yes ");
	}
	else
	{
		System.out.println("No");
	}
	
	//practice:
	//Problem 1: pass when compiling and fail when running
	//Example 1
//	Person p3 = new Woman();
//	Man m2 = (Man)p3;
	//Example 2
//	Person p4 = new Person();// It's not appropriate to think about it
//	Man m4 = (Man) p4;
//	m4.earnMoney();
	//
	
	
	//Question 2: it passes at compile time and at run time
	Object obj = new Woman();
	Person p = (Person)obj;
	
	//Question 3: compilation failed
//	Man m5 = new Woman();
//	String str = new Data();
	
	
}
}

42. Polymorphism exercise: calling properties and methods

package com.atshangguigu.Exer;

public class FieldMethodTest {
	public static void main(String[] args) {
		Sub s = new Sub();
		System.out.println(s.count);//20: What is called here is the method in Sub: the existence of proximity principle
		s.display();//20. The display() here is rewritten, but it still executes the code in the subclass
		
		Base b = s;//Assign the address value of s to b
		System.out.println(b == s);//Later, we will introduce = = in detail. Here we compare whether the address values of the two are the same
		System.out.println(b.count);//Here is the attribute. Is it polymorphic
		b.display();//Here is the method, which is polymorphic - the call of virtual method
	}
}

class Base {
	//attribute
	int count = 10;

	public void display() {
		System.out.println(this.count);
	}
}

class Sub extends Base {
	//Attribute: does not reflect polymorphism
	int count = 20;

	public void display() {
		System.out.println(this.count);
	}
}
  • Note here: properties with the same name and methods with the same name

  • Summary:

    1. If the subclass overrides the parent method, it means that the methods defined in the subclass completely cover the methods in the parent class
    If the method has the same name, it will be impossible for the system to transfer the method in the parent class to the child class
    2. For instance variables, there is no such phenomenon, even if the child class defines exactly the same as the parent class
    Instance variable. It is still impossible for this instance variable to override the instance variable defined in the parent class. (property)
  • Compile to the left, run to the right

43. Polymorphism exercise: basic operation

package com.atshangguigu.Exer;
/*
      Create an InstanceTest class and define the method(Person e) in the class;
In method:
(1)Call the getInfo() method of the corresponding class according to the type of e.
(2)According to the type of e:
If e is an object of Person class, output: "a person";
If e is an object of Student class, output:
"a student"
"a person " 
If e is an object of grade class, the output is:
"a graduated student"
"a student"
"a person"
 */
public class InstanceTest {
public static void main(String[] args) {
	InstanceTest test = new InstanceTest();
	test.method(new Student());//Virtual method call
	
}
	public void method(Person e)
	{
		//Virtual method call
		String info = e.getInfo();
		System.out.println(info);
		//Mode 1
		if(e instanceof Graduate)
		{
			System.out.println("a graduated student");
			System.out.println("a student");
			System.out.println("a person");
		}
		else if(e instanceof Student)
		{
			System.out.println("a student");
			System.out.println("a person");
		}
		else if(e instanceof Person)
		{
			System.out.println("a person");
		}
		//Mode II
		if(e instanceof Graduate)
		{
			System.out.println("a graduated student");
		}
		 if(e instanceof Student)
		{
			System.out.println("a student");

		}
		 if(e instanceof Person)
		{
			System.out.println("a person");
		}
		
	}
}

class Person {
	protected String name = "person";
	protected int age = 50;

	public String getInfo() {
		return "Name: " + name + "\n" + "age: " + age;
	}
}

class Student extends Person {
	protected String school = "pku";

	public String getInfo() {
		return "Name: " + name + "\nage: " + age + "\nschool: " + school;
	}
}

class Graduate extends Student {
	public String major = "IT";

	public String getInfo() {
		return "Name: " + name + "\nage: " + age + "\nschool: " + school + "\nmajor:" + major;
	}
}

44. Polymorphism exercise: geometry

  • The exercises are as follows:

  • Note: here # stands for protect
  • GeometricObject.java
package com.atshangguigu.Exer1;

public class GeometricObject {//Geometry
    //1. Properties
	protected String color;
	protected double weight;
	//2. Use of get and set
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	//3. Constructor
	public GeometricObject(String color, double weight) {
		super();
		this.color = color;
		this.weight = weight;
	}
	//Set the method
	public double findArea()//I can't write the area here. I can only use calculus
	{
		return 0.0;
	}
	
}
  •  Circle.java
package com.atshangguigu.Exer1;

public class Circle extends GeometricObject{
	//Note that an error is reported at the beginning, because the constructor in the previous parent class is null, so we need to introduce it here
	//1. Properties
	private double radius;
	//2. Constructor
	public Circle(double radius,String color, double weight) {
		super(color, weight);
		this.radius = radius;
	}
	//3.set and get methods
	public double getRadius() {
		return radius;
	}
	public void setRadius(double radius) {
		this.radius = radius;
	}
	//4. Method
	public double findArea()
	{
		return Math.PI*(this.radius)*(this.radius);
	}
	
	
}
  • MyRectangle.java
package com.atshangguigu.Exer1;

public class MyRectangle extends GeometricObject{
	
	//1. Properties
	private double height;
	private double weigh;
	//2. Constructor
	public MyRectangle(double height,double weigh,String color, double weight) 
	{
		super(color, weight);
		this.height = height;
		this.weight = weigh;
	}
	//3. Construction of set and get
	public double getHeight() {
		return height;
	}
	public void setHeight(double height) {
		this.height = height;
	}
	public double getWeigh() {
		return weigh;
	}
	public void setWeigh(double weigh) {
		this.weight = weigh;
	}
	//4. Calculate the area
	public double findArea()
	{
		return this.weight*this.height;
	}
	
}
  • GeometricTest.java
package com.atshangguigu.Exer1;
/*
Define a test class GeometricTest and write the equalsArea method to test whether the areas of two objects are equal
(Pay attention to the parameter type of the method and use dynamic binding technology),
Write the displayGeometricObject method to display the area of the object (pay attention to the parameter type of the method and use the dynamic binding technology).
 */
public class GeometricTest {

	public static void main(String[] args) {
		//This is a test of two circles
		GeometricTest test = new GeometricTest();
		Circle c1 = new Circle(4.0, "black", 12.4);
		test.displayGeometricObject(c1);
		Circle c2 = new Circle(4.0, "white", 12.4);
		test.displayGeometricObject(c2);
		
		boolean is = test.equalsArea(c1,c2);
		System.out.println("c1 and c2 Are the areas equal" + is);
	}
	
	//Test whether the two areas are equal
	public boolean equalsArea(GeometricObject o1,GeometricObject o2)
	{
		return o1.findArea() == o2.findArea();
	}
	//Displays the area of the object
	public void displayGeometricObject(GeometricObject o)
	{
		System.out.println("Area is:" + o.findArea());
	}
}

45. Polymorphism exercise: Rewriting methods

  •   The answer is: runtime behavior
package com.atshangguigu.Exer;

//Written examination questions for examination:
public class InterviewTest1 {

	public static void main(String[] args) {
		Base1 base = new Sub1();//I'm sorry
		base.add(1, 2, 3);//Here is the call from Sub1
		//Why? Because you can see that the code is drawn with a yellow line, it is rewritten, and from the running results, it is also rewritten

		Sub1 s = (Sub1)base;
		s.add(1,2,3);
		//Priority call determined
	}
}

class Base1 {
	public void add(int a, int... arr) {
		System.out.println("base1");
	}
}

class Sub1 extends Base1 {

	public void add(int a, int[] arr) {
		System.out.println("sub_1");
	}

	public void add(int a, int b, int c) {
		System.out.println("sub_2");
	}

}

46. Analysis of object class structure

//I didn't watch this video. I'll watch it later

47. = = operator review

48. Use of equals()

49. Override equals()

  • Manual rewriting - automatic generation is the same as the previous set and get
	//Override equals()
	//Rewriting principle: compare whether the entity contents of two objects are the same (there is no idea, so let's see how String is written)
	@Override
	public boolean equals(Object obj) {
		System.out.println("Has it been implemented?");
		if(this == obj)
		{
			return true;
		}
		if(obj instanceof Customer)
		{
			Customer cus = (Customer)obj;
			//Compare whether the properties of two objects are the same
			/*if(this.age == cus.age && (this.name.equals(cus.name)))
				//It should be noted here that the first one is = =, and the last one is equals(). Why is equals,
				//Because the following cus.name is a reference data type, you must use equals()
			{
				return true;
			}
			else
			{
				return false;
			}*/
			//Another way is
			return this.age == cus.age && this.name.equals(cus.name);
				
		}
		
		return false;
		
	}

50. Summarize equals and==

  • Cannot write null.equals(x);

  •   The '= =' symbol must indicate that the types on both sides are the same or consistent

51.equals() exercise 1: code implementation

package com.atshangguigu.Exer2;
/*
 * 1.Write an Order class with an orderId of type int, an orderName of type String, and the corresponding
getter()And setter() methods, two parameter constructors, override the equals() method of the parent class:
public boolean equals(Object obj),And judge the two objects created in the test class
 Whether they are equal.
 */
public class OrderTest {
	public static void main(String[] args) {
		Order order1 = new Order(1001,"AA");
		Order order2 = new Order(1000,"BB");
		
		System.out.println(order1.equals(order2));
		
		Order order3 = new Order(1000,"BB");
		System.out.println(order2.equals(order3));//Use = =. Note that generally, new cannot be used directly for String
		
		String s1 = "CC";
		String s2 = "CC";
		System.out.println(s1 == s2);//true
		
	}
}
class Order
{	//attribute
	private int orderId;
	private String orderName;
	//set and get
	public int getOrderId() {
		return orderId;
	}
	public void setOrderId(int orderId) {
		this.orderId = orderId;
	}
	public String getOrderName() {
		return orderName;
	}
	public void setOrderName(String orderName) {
		this.orderName = orderName;
	}
	//constructor 
	public Order(int orderId, String orderName) {
		super();
		this.orderId = orderId;
		this.orderName = orderName;
	}
	@Override
		public boolean equals(Object obj) {
			if(this == obj)
			{return true;
			}
			if(obj instanceof Order)
			{ //Downward transformation
				Order order = (Order)obj;
				//return this.orderId == order.orderId && this.orderName.equals(order.orderName);
				return this.orderId == order.orderId && this.orderName==order.orderName;
			}
			return false;
		}
}

52.equals() exercise 2: code implementation

package com.atshangguigu.Exer2;

public class MyDateTest {
	public static void main(String[] args) {
		MyDate m1 = new MyDate(14, 3, 1976);
		MyDate m2 = new MyDate(14, 3, 1976);
		if (m1 == m2) {
		System.out.println("m1==m2");
		} else {
		System.out.println("m1!=m2"); // m1 != m2
		}
		if (m1.equals(m2)) {
		System.out.println("m1 is equal to m2");// m1 is equal to m2
		} else {
		System.out.println("m1 is not equal to m2");
		} }
}
class MyDate
{	//attribute
	private int day;
	private int month;
	private int year;
	//get and set
	public int getDay() {
		return day;
	}
	public void setDay(int day) {
		this.day = day;
	}
	public int getMonth() {
		return month;
	}
	public void setMonth(int month) {
		this.month = month;
	}
	public int getYear() {
		return year;
	}
	public void setYear(int year) {
		this.year = year;
	}
	//constructor 
	public MyDate(int day, int month, int year) {
		super();
		this.day = day;
		this.month = month;
		this.year = year;
	}
	//rewrite
	public boolean equals(Object obj)
	{
		if(this == obj)
		{
			return true;
		}
		if(obj instanceof Object )
		{
			MyDate mydate = (MyDate)obj;
			return this.day == mydate.day && this.month == mydate.month && this.year == mydate.year;
			
		}
		return false;
	}
/*
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		MyDate other = (MyDate) obj;
		if (day != other.day)
			return false;
		if (month != other.month)
			return false;
		if (year != other.year)
			return false;
		return true;
	}
	*/
}

53. Use of tostring()

  • Rewrite in Customer.java
	public String toString() {
		return "Customer[name = "+ name + ",age = " + age + "]";
	}
  • Continue to write code in toString.java
package com.atshangguigu.java1;

import java.util.Date;

/*
 * Object Use of toString() in class:
 * 1.When we output a reference to an object, we actually call the toString() of the current object
 * 2.Object How toString() is defined in the class:
 *   public String toString() 
 *   {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());//Class name + @ + memory address (virtual)
    }
   3.The String Date File wrapper class overrides the toString method in Object
           This enables the "entity content" information to be returned when the toString() of the object is called
   4.A custom class can also override the toString() method and return the "entity content" of the object when this method is called
 */
public class toString {
public static void main(String[] args) {
	Customer cust = new Customer("Tom",12);
	System.out.println(cust.toString());//Output an address value com. Atshangguigu. Java1 Customer@15db9742
	System.out.println(cust);
	
	String str = new String("MM");
	System.out.println(str);//MM the String here has been rewritten, so it can output MM
	
	Date date = new Date(123456789L);
	System.out.println(date);//Fri Jan 02 18:17:36 CST 1970
}
	
}

54. Comprehensive practice of object class

  • GeomtricObject.java
package com.atshangguigu.Exer3;

public class GeometricObject {
	//1. Properties
	protected String color;
	protected double weight;
	//2. Here is a constructor
	public GeometricObject() {
		super();
		this.color = "white";
		this.weight = 1.0;
		
	}
	public GeometricObject(String color, double weight) {
		super();
		this.color = color;
		this.weight = weight;
	}
	//3.get and set settings
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	
}
  • Circle.java
package com.atshangguigu.Exer3;

public class Circle extends GeometricObject
{	//1. Properties
	private double radius;
	//2. Constructor
	public Circle() {
		super();
	//	this.color = "white";
		//this.weight = 1.0;
		this.radius =1.0;
	}
	public Circle(double radius) {
		super();
		this.color = "white";
		this.weight = 1.0;
		this.radius = radius;
	}
	public Circle(String color, double weight, double radius) {
		super(color, weight);
		this.radius = radius;
	}
	//3.set and get
	public double getRadius() {
		return radius;
	}
	public void setRadius(double radius) {
		this.radius = radius;
	}
	//4. Method
	public double findArea()//Calculate the area of a circle
	{
		return Math.PI*radius*radius;
	}
	//5. Rewrite
	@Override
		public boolean equals(Object obj) {
			if(this == obj)
			{
				return true;
			}
			if(obj instanceof Object)
			{
				Circle circle = (Circle)(obj);
				return this.radius == radius;
				
			}
			return false;
		}
	@Override
	public String toString() {
		return "Circle [radius=" + radius + "]";
	}
	
}
  • CircleTest.java
package com.atshangguigu.Exer3;

public class CircleTest {
public static void main(String[] args) {
	Circle c1 = new Circle("black",12 , 119);
	Circle c2 = new Circle("black",12 , 119);
	boolean isColor = c1.color.equals(c2.color);//This is protected, so it can be written like this, which is different from the video
	System.out.println("Is the color the same" + isColor);

	boolean isRadius = c1.equals(c2);
	System.out.println("Is the radius the same" + isRadius);
	
	System.out.println(c1.toString());
	System.out.println(c2.toString());

}
}

55. Use of unit test methods

  • Test the code where you want to test the code
package com.atshangguigu.java2;

import org.junit.Test;

/*
 * Java JUnit unit testing in
 * 
 * Steps:
 * 1.Select the current project - right click to select: build path - add libraries - JUnit 4 - next step (of course, the blogger's is different from that in the video. You can find it directly through Baidu, but the method is different)
 * 2.Create Java classes for unit testing
 *   The requirements for Java classes at this time are: 1. This class is public. 2. Provide a public parameterless constructor
 * 3.The test method of this kind of unit test
 *   This unit test method: the permission of the method is public, with no return value and no formal parameters
 * 4.This unit Test method needs to be annotated: @ Test, and imported into the unit Test class: import org.junit.Test;
 * 5.After declaring the code, you can test the relevant code inside the method
 * 6.After writing the corresponding code, double-click the selected unit test method name and right-click: run as - JUnit Test
 * 
 * explain:
 * 1.If there is no exception in the execution result, the execution result is a green bar; When there is an abnormality, it is a red bar --- stop at the red light and go at the green light
 * 2.
 */
public class JUnitTest {
	int num = 10;
	@Test
	public void testEquals()
	{
		String s1 = "MM";
		String s2 = "GG";
		System.out.println(s1.equals(s2));
		System.out.println(num);
		show();
	}
	public void show()
	{
		num = 20;
		System.out.println("show()........");
	}
	
	@Test
	public void testToString()
	{
		String s2 = "MM";
		System.out.println(s2);
		
	}
}
  • During the development process, directly @ Test and click it

56. Understanding of packaging

  • The basic data type is really thin
  • The basic data type has nothing to do with the Object. The basic data type is equivalent to a disabled person. Cure it. An int is needed in the Interger, which reflects the Object-oriented idea and Object-oriented function. Here we can explain which basic data type cannot be polymorphic in the process of polymorphism. (Saint fighter - it becomes very awesome to wear the holy coat of Sagittarius)

57. Convert basic data type to package type

  • Conversion between basic data type wrapper class and String class

package com.atshangguigu.java2;

import org.junit.Test;

/*
 * Use of packaging:
 * 1.java The wrapper classes corresponding to eight data types are provided, so that the variables of data types have the characteristics of classes
 * 2.Master: conversion between basic data type and packing class String
 */
public class WrapperTest {
	//How to convert a basic data type to a wrapper class: call the constructor of the wrapper class
	@Test
	public void test1()
	{
		int num1 = 10;
		Integer in1 = new Integer(num1);
		System.out.println(in1.toString());
		
		Integer in2 = new Integer("123");//It should be noted here that "" should be a pure number
		System.out.println(in2);
		/*
		Integer in2 = new Integer("123qwert");//It should be noted here that "" should be a pure number
		System.out.println(in2);
		*/
		Float f1 = new Float(12.3f);
		Float f2 = new Float("12.3");
		System.out.println(f1);
		System.out.println(f2);
		
		Boolean b1 = new Boolean(true);
		Boolean b2 = new Boolean("true");
		Boolean b3 = new Boolean("true1234");
		System.out.println(b2);
		System.out.println(b3);
		
		Order order = new Order();
		System.out.println(order.isMale);//false
		System.out.println(order.isFemale);//Null now it is a class, so it is null
	}
}
class Order
{
	boolean isMale;
	Boolean isFemale;
}

58. Convert package class to basic data type

	//2. Convert wrapper class to basic data type: call xxxValue() of wrapper class
	@Test
	public void test2()
	{
		Integer in1 = new Integer(12);
		int i1 = in1.intValue();
		System.out.println(i1 + 1);
		
		Float f1 = new Float(12.3);
		float f2 = f1.floatValue();
		System.out.println(f2 + 1);
		
	}

59. New features: automatic packing and automatic unpacking

/*
	 * JDK5.0 New features: automatic packing and automatic unpacking
	 */
	@Test
	public void test3()
	{
//		int num1 = 10;
//		//Basic data type --- object of wrapper class
//		method(num1);
		
		//Automatic packing:
		int num2 = 10;
		Integer in1 = num2;//There's no need for us to go to new here
		//Automatic packing
		boolean b1 = true;
		Boolean b2 = b1;
		
		//Automatic unpacking: convert packaging class to basic data type
		System.out.println(in1.toString());
		
		int num3 = in1;
		
	}
	public void method(Object obj)
	{
		System.out.println(obj);
	}
	
  • This implies a knowledge point: automatic packing and automatic unpacking, which are used in the company after jdk5.0

60. Conversion between basic data type wrapper class and String

	//3.2 how to convert string type to basic data type or wrapper class: call parseXxx() of wrapper class
	@Test
	public void test5()
	{
		String str1 = "456";//It can't be written as 456Yang here. Make sure the numbers can be converted
		//Wrong situation
		//int num1 = (int)str1;
		//Integer in1 = (Integer)str1;
		int num2 = Integer.parseInt(str1);
		System.out.println(num2 + 23);
		
		String str2 = "false";//As long as it is not true, it is false
		boolean b1 = Boolean.parseBoolean(str2);
		System.out.println(b1);
		
	}
	//3.1 how to convert basic data type to String type: call valueof (XXX, XXX) overloaded by String
	@Test
	public void test4()
	{
		//Mode 1: connection operation
		int num1 = 10;
		String str1 = num1 + "";//Basic data type + "" (string)
		//Method 2: call valueOf() of String
		float f1 = 12.3f;
		String str2 = String.valueOf(f1);//"12.3"
		System.out.println(str2);
		
		Double d1 = new Double(12.4);
		String str3 = String.valueOf(d1);//"12.4"
		System.out.println(str3);
	}

61. Packaging common interview questions

package com.atshangguigu.java2;

import org.junit.Test;

/*
 * Interview questions about the use of packaging
 * 
 */
public class Interview {
	@Test//First, you need to guide the package: ctrl + shift + o
	public void test1() {
		Object o1 = true ? new Integer(1) : new Double(2.0);
		//The above formula has a type of promotion, so Integer(1) becomes Double()
		System.out.println(o1);//1.0
	}

	@Test
	public void test2() {
		Object o2;
		if (true)
			o2 = new Integer(1);
		else
			o2 = new Double(2.0);
		//There is no unification of results above
		System.out.println(o2);//1
	}
	
	@Test
	public void method1() {
		Integer i = new Integer(1);
		Integer j = new Integer(1);
		System.out.println(i == j);//false = = address
		Integer m = 1;
		Integer n = 1;
		System.out.println(m == n);//true
		Integer x = 128;
		Integer y = 128;
		System.out.println(x == y);//false
		}
	//The above question is difficult -- implicit knowledge points
	//The built array stores a lot of numbers - 128 - 127. The reason why the array is built here is convenient to use, but when it exceeds 127, a new 128 will be created
	//The above is new. There are two 128
	
}

62. After class exercises in packaging

Almost. Write it tomorrow

63. Daily test

Tags: Java Eclipse

Posted on Thu, 21 Oct 2021 21:09:31 -0400 by markvaughn2006