1. Inheritance
1.1 implementation of inheritance (mastery)
The concept of inheritance
Inheritance is one of the three characteristics of object-oriented. It can make the subclass have the properties and methods of the parent class. It can also be redefined in the subclass, and the format of inheritance can be implemented by appending the properties and methods
Inheritance is implemented through extensions
Format: class subclass extends parent class {}
For example: class Dog extends Animal {}
public class Fu { public void show() { System.out.println("show Method called"); } } public class Zi extends Fu { public void method() { System.out.println("method Method called"); } } public class Demo { public static void main(String[] args) { //Create object, call method Fu f = new Fu(); f.show(); Zi z = new Zi(); z.method(); z.show(); } }
1.2 advantages and disadvantages of inheritance (understanding)
Inheritance benefits
Improves code reusability (members of the same class can be placed in the same class)
Improve the maintainability of the code (if the code of the method needs to be modified, just modify one place)
Disadvantages of inheritance
Inheritance creates a relationship between classes and enhances the coupling of classes. When the parent class changes, the implementation of the subclass also has to change, weakening the application scenario of independent inheritance of the subclass:
Using inheritance, we need to consider whether is exists between classes The relation of a, can't use inheritance blindly
is… a relationship: who is who, for example: teachers and students are human, that person is the parent, and students and teachers are subclasses
2. Access characteristics of members in inheritance
2.1 access characteristics of variables in inheritance
To access a variable in a subclass method, the principle of proximity is adopted.
- Subclass local range finding
- Subclass member scope
- Parent class member scope search
- If they don't, they will report a mistake (regardless of their father's father)
class Fu { int num = 10; } class Zi { int num = 20; public void show(){ int num = 30; System.out.println(num); } } public class Demo1 { public static void main(String[] args) { Zi z = new Zi(); z.show(); // Output local variables in the show method 30 } }
2.2 super
This & Super keyword:
This: refers to the object of this class
Super: indicates the storage space of the parent class (which can be understood as the reference of the parent class object). this and super are used respectively
Member variable:
This. Member variable - access this type of member variable
super. Member variable - access parent member variable
Member method:
This. Member method - access member methods of this class
super. Member method - access parent member method
Construction method:
this(… )- access the construction method of this class
super(… )- access the parent class constructor
2.3 access characteristics of construction methods in inheritance (understanding)
Note: by default, all construction methods in the subclass will access the construction methods without parameters in the parent class
The child class inherits the data from the parent class and may also use the data from the parent class. Therefore, before the initialization of a subclass, the initialization of the parent class data must be completed first. The reason is that the first statement of each subclass construction method defaults to super()
Question: if there is no nonparametric construction method in the parent class, only with parameter construction method, what should we do?
- Construction method of calling parent class with parameters by using super keyword to display
- Provide a nonparametric construction method in the parent class
Recommended scheme: give the method of nonparametric construction
2.4 access characteristics of member methods in inheritance
Accessing a method through a subclass object
- Subclass member scope
- Parent class member scope search
- If not, report the mistake )
2.5 super memory map (understanding)
Object in heap memory, there will be a separate super area to store the data of the parent class
2.6 method rewriting (mastery)
1. Method rewrite concept
Subclass as like as two peas in the parent class, the same method declaration (the same as the method name, the parameter list must be the same).
2. Application scenario of method rewriting
When the subclass needs the function of the parent class, and the function subject subclass has its own specific content, the method in the parent class can be overridden. In this way, the function of the parent class is followed, and the specific content of the subclass is defined
3. Override annotation
It is used to check whether the current method is a rewritten method and plays the role of verification
2.7 precautions for method rewriting
Method rewriting considerations
- Private method cannot be overridden (parent private member subclass cannot inherit)
- Subclass method access permission cannot be lower (public > Default > private)
public class Fu { private void show() { System.out.println("Fu in show()Method called"); } void method() { System.out.println("Fu in method()Method called"); } } public class Zi extends Fu { /* Compile [error], the subclass cannot override the private method of the parent class*/ @Override private void show() { System.out.println("Zi in show()Method called"); } /* Compile [error], when the subclass overrides the parent method, the access permission must be greater than or equal to the parent */ @Override private void method() { System.out.println("Zi in method()Method called"); } /* Compile pass. When a subclass overrides a parent method, the access permission must be greater than or equal to the parent */ @Override public void method() { System.out.println("Zi in method()Method called"); } }
2.8 precautions for inheritance in Java
Notes on inheritance in Java
- Classes in Java only support single inheritance, not multiple inheritance
Error example: class A extends B, C {} - Classes in Java support multi inheritance and multi inheritance example code:
public class Granddad { public void drink() { System.out.println("Grandpa likes drinking"); } } public class Father extends Granddad { public void smoke() { System.out.println("Dad likes smoking"); } } public class Mother { public void dance() { System.out.println("Mom loves dancing"); } } public class Son extends Father { // At this point, the Son class has both the drive method and the smoke method }
3. Inheritance exercise
3.1 teachers and students (application)
Requirements: define teacher class and student class, then write code test; finally, find out the common content between teacher class and student class, extract a parent class, rewrite the code by inheritance, and carry out test steps:
① Define teacher class (name, age, teaching ())
② Define student class (name, age, study ())
③ Define test class, write code test
④ Generic extraction of parent class, definition of human (name, age)
⑤ Define teacher class, inherit human, and give your own unique method: teach ()
⑥ Define student classes, inherit human beings, and give their own unique methods: Learning ()
⑦ Define the test class, write the code test sample code:
class Person { private 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; } } class Teacher extends Person { public Teacher() {} public Teacher(String name,int age) { super(name,age); } public void teach() { System.out.println("Achieve every student with love"); } } class Student extends Person{ public Student() {} public Student(String name, int age) { super(name,age); } public void study(){ System.out.println("Student learning"); } } class PersonDemo { public static void main(String[] args){ //Create a teacher class object and test it Teacher t1 = new Teacher(); t1.setName("Zhang San"); t1.setAge(30); System.out.println(t1.getName() + "," + t1.getAge()); t1.teach(); Teacher t2 = new Teacher("Li Si", 33); System.out.println(t2.getName() + "," + t2.getAge()); t2.teach(); // Create student class object test Student s = new Student("Wang Wu",23); System.out.println(s.getName() + "," + s.getAge()); s.study(); } }
3.2 cat and dog (application)
Requirements: please use the idea of inheritance to implement the case of cat and dog, and test and analyze in the test class: ① cat:
Member variable: name, age construction method: no parameter, with parameter
Member method: get/set method, catch mouse ()
② Dog:
Member variable: name, age construction method: no parameter, with parameter
Member method: get/set method, gatekeeper ()
③ Common:
Member variable: name, age; construction method: no parameter, with parameter; member method: get/set method step:
1. Define animal class
[member variable: name, age] [construction method: no parameter, with parameter] [member method: get/set method]
2. Define cat, inherit animal class
[construction method: no parameter, with parameter] [member method: catch mouse ()]
3. Define dog, inherit animal class
[construction method: no parameter, with parameter] [member method: guard door ()]
4. Define the test class (AnimalDemo), write code test sample code:
class Animal { private String name; private int age; public Animal() { } public Animal(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; } } class Cat extends Animal { public Cat() { } public Cat(String name, int age) { super(name, age); } public void catchMouse() { System.out.println("Cat catches mouse"); } } class Dog extends Animal { public Dog() { } public Dog(String name, int age) { super(name, age); } public void lookDoor() { System.out.println("Dog watch"); } }/ * //Test class */ public class AnimalDemo { public static void main(String[] args) { //Create cat objects and test them Cat c1 = new Cat(); c1.setName("Garfield"); c1.setAge(5); System.out.println(c1.getName() + "," + c1.getAge()); c1.catchMouse(); Cat c2 = new Cat("Garfield", 5); System.out.println(c2.getName() + "," + c2.getAge()); c2.catchMouse(); } }
4. Modifier
4.1 package (understanding)
1. The concept package of a package is a folder, which is used to manage class files
2. Package definition format
Package name; (multi-level package. Separate) for example: package com.wan.demo ;
3. Compile with package & run with package
Compile with package: javac - d. class name. Java for example: javac - d com.wan.demo . HelloWorld.java
Run with package: java package name + class name
For example: java com.wan.demo.HelloWorld
4.2 import (understanding)
When using classes under different packages, you need to write the full path of the class. It's too cumbersome to write. In order to simplify the operation with packages, Java provides the format of the function package
Format: import package name;
Example: import java.util.Scanner ;
Sample code (Scanner object created without using the import package)
package com.wan; public class Demo { public static void main(String[] args) { // 1. Create Scnaner object without package java.util.Scanner sc = new java.util.Scanner(System.in); } }
Scanner object created after using the import package
package com.wan; import java.util.Scanner; public class Demo { public static void main(String[] args) { // 1. Create Scnaner object without package Scanner sc = new Scanner(System.in); } }
4.3 authority modifier (understanding)
4.4 final (application)
The function of fianl keyword
Final represents the final meaning. It can modify member methods, member variables, and class final to modify the effects of classes, methods, and variables
fianl modifier class: this class cannot be inherited (it cannot have children, but it can have parents)
final decorated method: this method cannot be overridden
final modifier variable: indicates that the variable is a constant and cannot be assigned again
4.5 final modify local variables (understanding)
fianl decorated basic data type variable
final decoration means that the data value of the basic type cannot be changed
final modifier references data type variables
final decoration means that the address value of the reference type cannot be changed, but the content in the address can be changed
give an example:
public static void main(String[] args){ final Student s = new Student(23); s = new Student(24); // error s.setAge(24); // correct }
4.6 static (application)
The concept of static
Static keyword means static. It can modify the characteristics of static modification of member method and member variable
- It is shared by all objects of the class, which is also the condition for us to judge whether to use static keywords
- It can be called by class name, of course, or by object name
Example code:
class Student { public String name; //full name public int age; //Age public static String university; //Schools share data! So the design is static! public void show() { System.out.println(name + "," + age + "," + university); } } public class StaticDemo { public static void main(String[] args) { // Assign a value to the shared data of an object Student.university = "Tsinghua University"; Student s1 = new Student(); s1.name = "Zhang San"; s1.age = 23; s1.show(); Student s2 = new Student(); s2.name = "Li Si"; s2.age = 21; s2.show(); } }
4.7 static access features (mastery)
Access characteristics of static
Non static member methods
Access to static member variables
Access to non static member variables
Access to static member methods
Access to non static member methods
Static member methods
Access to static member variables
Access to static member methods
To sum up, a static member method can only access static members