0x00 overview
This article deals with Java knowledge points for inheritance and modifiers
0x01 inheritance
1.1 implementation of inheritance
- Concept of inheritance
Inheritance is one of the three characteristics of object-oriented. It can make subclasses have the properties and methods of the parent class, redefine them in subclasses, and append properties and methods.
- Implement inherited formats
Inheritance is implemented through extensions
Format: class subclass extends parent class {}
Example: class dog extends Animal {}
- Benefits of inheritance:
Inheritance can create a relationship between classes and a child parent relationship. After generating a child parent class, the child class can use the non private members of the parent class.
Example
package com.superTest1; public class Fu { public void show() { System.out.println("Fu show()Method called"); } }
package com.superTest1; public class Zi extends Fu{ public void method() { System.out.println("Zi method Method called"); } }
package com.superTest1; public class Demo { public static void main(String[] args) { // Create an object and call a method Fu f = new Fu(); f.show(); Zi z = new Zi(); z.method(); z.show(); } }
Output results
/* Fu show()Method called Zi method Method called Fu show()Method called */
1.2 advantages and disadvantages of inheritance
- Benefits of inheritance
Provides code reusability (the same members of multiple classes can be placed in the same class)
The maintainability of the code is improved (if the method code 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 subclasses has to change, weakening the independence of subclasses
- Inherited application scenarios
When using inheritance, you need to consider whether there is an is a relationship between classes. Inheritance cannot be used blindly
The relationship between is a and who is who. For example, teachers and students are one kind of people, that person is the parent class, and students and teachers are both subclasses
0x02 member access characteristics in inheritance
2.1 access characteristics of variables in inheritance
The proximity principle is used to access a variable in subclass methods
1. Local range finding of subclass
2. Subclass member range
3. Parent member range cannot be found
4. If there is none, an error is reported (regardless of the parent class of the parent class)
Example
package com.superTest2; public class Fu { int num = 10; }
package com.superTest2; public class Zi extends Fu { int num = 20; public void show() { int num = 30; System.out.println(num); } }
package com.superTest2; public class Demo { public static void main(String[] args) { Zi z = new Zi(); z.show(); } }
output
30
2.2 super
- This & Super keyword:
This: represents the reference of this class object
super: represents the identification of the storage space of the parent class (which can be understood as the reference of the parent class object)
- The use of this & super is as follows:
Member variables:
This. Member variable - access the member variable of this class
super. Member variables - access parent member variables
Member method:
This. Member method - access the member method of this class
super. Member method - access parent class member method
- Construction method:
this(...) - access the constructor of this class
super(...) - access the parent class constructor
2.3 access characteristics of construction methods in inheritance
Note: all constructors in the subclass will access the parameterless constructors in the parent class by default,
Subclasses inherit the data in the parent class and may use the data of the parent class. Therefore, before subclass initialization, you must complete the initialization of the parent class data,
The reason is that the first clause of each subclass construction method defaults to super(), which inherits the superclass Object (the Object class can be used by itself)
Question:
If there is no parameterless constructor in the parent class, what should we do as long as we construct the method with parameters?
/* 1 Use the super keyword to explicitly call the parameterized constructor of the parent class 2 Provide a parameterless constructor in the parent class */
Recommended scheme:
The method of nonparametric construction is given
2.4 access characteristics of member methods in inheritance
Accessing a method through a subclass object
1. Subclass member range
2. Parent member range cannot be found
3. If there is none, an error will be reported (regardless of the parent class of the parent class)
2.5 super memory diagram
- In heap memory, there will be a separate super area for storing the data of the parent class
2.6 method rewriting
1. Method rewrite concept
Subclass has the first mock exam (like the method name), and the parameter list must be the same as the parent class.
2. Application scenario of method rewriting
When the subclass needs the function of the parent class and the function subject class has its own unique content, you can override the methods in the parent class. In this way, it follows
The function of the parent class defines the specific content of the child class
3. Override annotation
It is used to detect whether the current method is an rewritten method and plays the role of verification
2.7 precautions for method rewriting
Method rewrite considerations:
1. Private methods cannot be overridden (private members of the parent class cannot inherit when subclassing)
2. Subclass method access permission cannot be lower (public > Default > private)
Example
package com.superTest3; public class Fu { private void show() { System.out.println("Fu in show()Method called"); } void method() { System.out.println("Fu in method()Method called"); } }
package com.superTest3; public class Zi extends Fu { /* // Compilation failed. When a subclass overrides the parent method, it cannot override the private method of the parent @Override public void show() { System.err.println("Zi The show() method is called in ""); } // Compilation fails. When the subclass overrides the parent class method, the access permission must be greater than or equal to the parent class @Override private void method() { System.out.println("Zi The method() method is called in ""); } */ @Override public void method() { System.out.println("Zi in method()Method called"); } }
2.8 considerations for inheritance in Java
Considerations for integration in Java
1. Classes in Java only support single inheritance, not multiple inheritance
Error example: class A extends B,C {}
2. Classes in Java support multi-layer inheritance
Example
package com.superTest4; public class Granddad { public void drink() { System.out.println("Grandpa likes drinking"); } }
package com.superTest4; public class Father extends Granddad{ public void smoke() { System.out.println("Dad likes smoking"); } }
package com.superTest4; public class mother { public void dance() { System.out.println("Mother loves dancing"); } }
package com.superTest4; public class Son extends Father { // At this point, the son class has both drink and smoke methods }
0x03 inheritance exercise
3.1 teachers and students
Requirements: define teacher class and student class, and then write code for testing; Finally, find the common content between teacher class and student class, extract a parent class, rewrite the code by inheritance, and test it
Steps:
1. Define teacher category (name, age, teaching ())
2. Define student category (name, age, study ())
3. Define test classes and write code for testing
4. Commonness extraction parent class to define human (name, age)
5. Define the teacher class, inherit human beings, and give their own unique methods to teach ()
6. Define students, inherit human beings, and give their own unique methods to learn ()
7. Define test classes and write code for testing
Example:
package com.extendTest1; public 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; } }
package com.extendTest1; class Teacher extends Person { public Teacher() { } public Teacher(String name, int age) { super(name, age); } public void teach() { System.out.println("Teachers can teach"); } }
package com.extendTest1; public class Student extends Person { public Student() { } public Student(String name, int age) { super(name, age); } public void study() { System.out.println("Learn to learn"); } }
package com.extendTest1; public class PersonDemo { public static void main(String[] args) { // Create a teacher class object and test it Teacher t1 = new Teacher(); t1.setName("Alice"); t1.setAge(33); System.out.println(t1.getName() + ", " + t1.getAge()); t1.teach(); Teacher t2 = new Teacher(); t2.setName("Bob"); t2.setAge(25); System.out.println(t2.getName() + ", " + t2.getAge()); t1.teach(); // Create student class objects for testing Student s1 = new Student("Charlie", 12); System.out.println(s1.getName() + ", " + s1.getAge()); s1.study(); } }
3.2 cats and dogs
Requirements: please use the idea of inheritance to implement the cat and dog case and test it in the test class
analysis:
1. Cat:
Member variables: name, age
Construction method: no parameter, with parameter
Member method: get/set method, catch mouse ()
2. Dog
Member variables: name, age
Construction method: no parameter, with parameter
Member method: get/set method, guard ()
Steps:
1. Define Animal
Member variables: name, age
Construction method: no parameter, with parameter
Member method: get/set method
2. Define Cat and inherit animal
Construction method: no parameter, with parameter
Member method: get/set method, catch mouse ()
3. Define dogs and inherit animals
Construction method: no parameter, with parameter
Member method: get/set method, guard ()
4. Define the test class (AnimalDemo) and write code for testing
Example
package com.extendTest2; public 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; } }
package com.extendTest2; public class Cat extends Animal { public Cat() { } public Cat(String name, int age) { super(name, age); } public void catchMouse() { System.out.println("Cat catches mouse"); } }
package com.extendTest2; public class Dog extends Animal { public Dog() { } public Dog(String name, int age) { super(name, age); } public void lookDoor() { System.out.println("Dog watch"); } }
package com.extendTest2; public class AnimalDemo { public static void main(String[] args) { // Create cat objects for testing Cat c1 = new Cat(); c1.setName("Garfileds"); c1.setAge(2); System.out.println(c1.getName()+", "+c1.getAge()); c1.catchMouse(); // Create dog objects for testing Dog d1 = new Dog(); d1.setName("wangwang"); d1.setAge(4); System.out.println(d1.getName()+", "+d1.getAge()); d1.lookDoor(); } }
0x04 modifier
4.1 package
1. Concept of package
A package is a folder used to manage class files
2. Definition format of package
Package name; (multi-level package. Separate)
For example: package.com.heima.demo;
3. Compile with package & run with package
Compiled with package: java -d. Class name. java
For example: Java -d. Com.heima.demo.helloworld.java
Running with package: java package name + class name
For example: java com.heimademo.HelloWorld
4.2 import
- Significance of guided packet
When using classes under different packages, it is too troublesome to write the full path of the class
In order to simplify the operation with package, java provides the function of guiding package
- Format of import package
Format: import package name;
Example: import java.util.Scanner;
Example (Scanner object created without import package)
package com.heima; public class Demo { public static void main(String[] args) { // 1. There is no import package. Create a Scanner object java.util.Scanner sc = new java.util.Scanner(System.in); } }
Example (create a Scanner object using the import package)
package com.heima; import java.util.Scanner; public class Demo { public static void main(String[] args) { // 1 create a Scanner object using the import package Scanner sc = new Scanner(System.in); } }
4.3 permission modifier
4.4 final
- Function of final keyword
Final stands for the final meaning. It can modify member methods, member variables and classes
- final modifies the effects of classes, methods, and variables
final modifier class. This class cannot be inherited, cannot have subclasses, but can have parent classes
final modifier method, which cannot be overridden
final modifies a variable, indicating that the variable is a constant and cannot be assigned again
4.5 final modifier local variable
- final modifies the basic data type variable
The final modifier means that the data value of the section type cannot be changed
- The final modifier refers to a data type variable
The final modification means that the address value of the reference type cannot be changed, but the content in the address can be changed
Example
public static void main(Sring[] args) { final Student s = new Student(23); s = new Student(25); s.setAge(26) ; }
4.6 static
- Concept of static
Static keyword means static. It can modify member methods and member variables
- Characteristics of static modification
1. Shared by all objects of the class, which is also the condition for us to judge whether to use static keywords
2. It can be called by class name or object name (class name is recommended)
Example
package com.staticDemo; public class Student { public String name; public int age; // The school is designed to share data, so it is designed to be static public static String university; public void show() { System.out.println(name + ", "+ age + "," + university ); } }
package com.staticDemo; public class staticDemo { public static void main(String[] args) { // Shared values for objects Student.university = "XX university"; Student s1 = new Student(); s1.name = "Alice"; s1.age = 30; s1.show(); Student s2 = new Student(); s2.name = "Bob"; s2.age = 32; s2.show(); } }
4.7 static access features
static access features
- Non static member method
Can access static member variables
Can access non static member variables
Access to static member methods
Access to non static member methods
- Static member method
Can access static member variables
Access to static member methods
- Summary:
Static member methods intelligently access static members