1, Package
1. Package overview
Package is the way to organize classes. The main purpose of using package is to ensure the uniqueness of classes.
If the path is different, it is unique. For example, if a colleague writes a class with the same name with you, it will lead to conflict and failure of compilation
A package is actually a folder
2. Use system package
1. Use the import package method to use the system package
In the java folder, there is such a file (usually a compressed file, which is the decompressed file) that stores the package in the java source code
Header files like this are called import packages
When using *, import all packages (automatically when you use that package)
2. Import the package without using the system package
Example:
Use this method to import and mark the path.
3. Use of duplicate packages
import java.util.*; import java.sql.*;
Having the Date class in both packages will lead to ambiguity, so that the compiler cannot recognize it. In this case, you cannot import the system package, but you must write the complete class name
4. Import static package (not recommended)
import static java.lang.System.*;
This import is a static import. After importing this package, the commonly used print function can be written like this
out.println("haha");
5. Common systems
import java.lang.*;//The basic classes commonly used in the system (String and Object), which are automatically imported from JDK1.1. import java.lang.reflect.*;//Reflection programming package; import java.net.*;//Development package for network programming import java.sql.*;//Development package for database programming import java.util.*;//Is a tool package provided by java. (collection class, etc.) import java.io.*;//I/O programming development kit.
2, Extensions
1. Initial understanding of succession
When writing a class, you may have many of the same properties and methods.
Example:
class dog{ public String name; public int age; public void eat(){ System.out.println("chi()"); } public void crow(){ System.out.println("wangwang"); } } class cat{ public String name; public int age; public void eat(){ System.out.println("chi()"); } public void fly(){ System.out.println("fly()"); } }
At this time, you can use inheritance to wrap the same properties or methods and inherit from other classes
class animal{ public String name; public int age; public void eat(){ System.out.println("chi()"); } } class dog extends animal{ public void crow(){ System.out.println("wangwang"); } } class bird extends animal{ public void fly(){ System.out.println("fly()"); } }
In the above example:
dog class extends animal
At this time
dog: subclass and derived class
animal: parent class, base class, superclass
2. Benefits of inheritance
Code can be reused.
3.private modification parameters
If a parameter or method in the parent class method is modified by private, it cannot be used.
class animal{ private String name; public int age; public void eat(){ System.out.println("chi()"); } } public static void main(String[] args) { Dog dog = new Dog(); System.out.println(dog.name+"hh"); }
At this time, an error will be reported when calling.
4. (interview question) what does the subclass inherit from the parent class?
A: everything except the constructor is inherited.
5.super keyword
To construct a subclass, you need to help the parent object construct first (call the construction method of the parent class).
class Animal{ private String name; public int age; public void eat(){ System.out.println("chi()"); } public Animal(String name){ this.name=name; } } class Dog extends Animal{ public String sex; public Dog(String name,String sex){ super(name); //Note: when super is used to construct a parent class, it should be placed in the first line, otherwise an error will be reported. this.sex=sex; } public void crow(String name){ System.out.println("wangwang"); } }
Otherwise, the program will report an error.
There are three ways to use super:
- super(): call the constructor of the parent class (must be placed on the first line)
- super.data: call the member property of the parent class
- super.func: call the member method of the parent class
6. Code execution sequence
- static {} of parent class
- static {} of subclass
- Instance code block of parent class {}
- Constructor of parent class
- Subclass instance code block {}
- Constructor for subclasses
Static must be executed first and only once.
7. Complex inheritance
class A{ } class B extends A{ } class C extends B{ } class D extends C{ }
Note: this inheritance relationship should not exceed three layers at most. If you don't want to be inherited, you need to use final to modify it to prevent it from being inherited.
8. Considerations for succession
- Using extensions
- A subclass in Java can only inherit one parent class
- Subclasses inherit all public fields and methods of the parent class
- For the private methods and fields of the parent class, the child class is inaccessible (not inheritable)
9. Distribution of attributes with the same name during inheritance
class A{ public int a = 1; } class B extends A{ public int a = 2; public int b = 3; } public class testw { public static void main(String[] args) { B b = new B(); System.out.println(b.a); } }
When calling a at this time, the a of the child class will be called instead of the a of the parent class.
3, Access modifier qualifier
Public: public permission
All files are accessible
Private: private permission
Can only be accessed in the current class
Protected: protected permissions
Used during inheritance. protected attributes or methods in the parent class can be called when subclasses in different packages inherit the parent class. They can be called using the super keyword
Default: default package access
Can only be accessed in the current package
4, final:
- final to modify the constant, int a = 10;
- final is used to modify the class. final class A {}. This class is called a sealed class and is not used when it wants to be inherited.
- final to modify the method, which is called the sealing method.
5, Combination
Relationships like the following are called combinations
class Student{ //class } class teacher{ //class } class school{ public Student[] student; public teacher[] teacher; }
6, Polymorphism
Literally: one thing has many forms
1. Upward transformation
Subclass object to parent class
Animal animal = new Dog("Zhang San");
Note:
Create variable a in Dog subclass object;
Create a variable b in the Animal parent class;
Animal animal = new Dog("Zhang San"); System.out.println(animal.b); System.out.println(animal.a); //An error is reported. The parent object cannot call the child object Dog dog = new Dog("Li Si"); System.out.println(dog.b); System.out.println(dog.a);
At this time, the type of animal is animal, so you can only access its own members.
Three opportunities for upward Transformation:
- Direct assignment:
Animal animal = new Dog("Zhang San");
- Value transfer:
public static void main(String[] args) { func(animal); //These three kinds of change upward func(dog); func(new Dog("Wang Wu")); } public static void func(Animal animal){ }
- Return value:
public static void main(String[] args) { Animal animal1 = func1(); } public static Animal func1(){ Dog dog = new Dog("Zhang San"); return dog; }
2. Downward transformation
Parent object to child
public static void main(String[] args) { Animal animal = new Dog("Zhang San"); Dog dog = (Dog) animal; dog.crow(); }
matters needing attention:
public static void main(String[] args) { Animal animal = new Animal("Zhang San"); Dog dog = (Dog) animal; dog.crow(); }
At this time, the code will report an error and report a type conversion error
Therefore, downward transformation must be carried out upward transformation.
Avoid wrong modifications:
//Judge whether animal is an instance of Dog. if(animal instanceof Dog){ Dog dog = (Dog) animal; dog.crow(); }
Returns true if Dog is referenced by animal, otherwise false.
It's safe.
3. Rewrite
class Animal{ public void eat(){ System.out.println("chi()"); } } class Dog extends Animal{ @Override //Note: the identity has been rewritten here public void eat() { System.out.println("he()"); } } public static void main(){ Animal animal = new Dog("tearful"); animal.eat(); }
overload
1. Same method name
2. Different parameter lists (number and type)
3. The return value is not required
override
1. Same method name
2. The parameter list is the same (number and type)
3. The return value is the same (if the return value constitutes a covariant type)
Covariant type: the return value between the child class and the parent class is an inheritance relationship
class Animal{ public Animal eat(){ System.out.println("chi()"); return new Animal("floret"); } } class Dog extends Animal{ @Override public Dog eat() { System.out.println("he()"); return new Dog("huahua"); } }
This constitutes a covariant type
Dynamic binding:
1. There must be upward transformation
2. Parent and child classes have override (override / overwrite) methods with the same name
3. Finally, the override method with the same name of the child class and the parent class is called through the reference of the parent class.
Dynamic binding, or runtime binding, occurs.
Note: dynamic binding (a pit) can also occur in the constructor
class Animal{ public void eat(){ System.out.println("chi()"); } public Animal(String name){ eat(); //Dynamic binding occurs this.name=name; } } class Dog extends Animal{ public Dog(String name){ super(name); } public void eat() { System.out.println("he()"); } } public static void main(String[] args) { Animal animal = new Dog("tearful"); }
At this time, dynamic binding occurs in the parent class constructor
Considerations for rewriting
1. If the current method is static, it cannot be overridden
2. If the subclass wants to override the parent method, the access modification permission of the subclass must be greater than or equal to the permission of the parent
3. The method to be overridden in the parent class must not be private.
4. The method modified by final cannot be rewritten (sealing method).
4. Understanding polymorphism
class Shape{ public void draw(){ } } class Cycle extends Shape{ public void draw(){ //To override the parent method System.out.println("rectangle"); } } class Rect extends Shape{ public void draw(){ //Override parent method System.out.println("circular"); } } public class testDome { public static void drawMap(Shape shape){ shape.draw(); //Call the parent class method, override the subclass method, and dynamically bind and print the subclass method } public static void main(String[] args) { Cycle cycle = new Cycle(); //new subclass object Rect rect = new Rect(); //new subclass object drawMap(cycle); //Upward transformation occurs during parameter transmission drawMap(rect); //Upward transformation occurs during parameter transmission } }
7, Abstract class
A class that contains abstract methods is an abstract class
What is an abstract method: a method modified by the keyword abstract. This method can have no specific implementation.
abstract class Shape{ //Sealing class public abstract void draw(); //Sealing method }
Considerations for abstract classes
- Abstract classes can be inherited, dynamically bound and transformed upward.
- Abstract classes cannot be instantiated
- Methods in abstract classes must be overridden by subclasses
- Abstract classes exist in order to be inherited, because they cannot be instantiated
- If an abstract class inherits an abstract class, the abstract method may not be overridden. However, if this abstract class is inherited by an ordinary class again, you need to override the abstract method.
- Abstract methods cannot be private
- Can include common methods
- Abstract classes cannot be final decorated.
8, Interface
Use the keyword interface to decorate.
1. Interface details
- The method in the interface is public abstract by default, and there can be no concrete implementation
- Interface cannot be instantiated
- The method in the interface defaults to public static final
- The direct relationship between class and interface is implements. At this time, all methods in the interface must be overridden.
- Interfaces can also be transformed upward - runtime binding (dynamic binding)
- Starting from JDK 1.8, the methods in the interface can have specific implementation, but this method must be modified by default.
- In Java, a class can implement multiple interfaces.
- Classes and interfaces are implements, and interfaces and interfaces are extensions
interface IShape{ //Interface int a = 10; //The default parameter is public static final void draw(); //Method defaults to public abstract default void func1(){ //There is a specific implementation of the method in the jdk1.8 start interface. This method must be modified by default. System.out.println("123"); } } class Cycle implements IShape{ @Override public void draw(){ System.out.println("○"); } } public class testDome { public static void func(IShape iShape){ iShape.draw(); } public static void main(String[] args) { //IShape iShape = new IShape(); // Cannot instantiate IShape iShape = new Cycle(); //Upward transformation func(iShape); } }
interface A{ } interface B{ } interface C extends A,B{ }
2.Comparable interface
When using custom types, use the Comparable interface
class Student implements Comparable<Student>{ public String name; public int age; public Student(String name,int age){ this.name = name; this.age = age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public int compareTo(Student o) { //Sort customized data //Comparison rules /*if (this.age > o.age){ return 1; //positive }else if (this.age > o.age){ return -1; }else{ return 0; }*/ //return this.age - o.age; // simplified method return this.name.compareTo(o.name); //Practiced the compareTo method in String } } public class testDome { public static void main(String[] args) { Student[] student = new Student[3]; student[0] = new Student("caocao",18); student[1] = new Student("liubei",26); student[2] = new Student("sunquan",22); Arrays.sort(student); //Array sorting System.out.println(Arrays.toString(student)); //Array printing } }
3. Comparator
//Class does not implement the interface as the Student above. //Different classes of the same package public class AgeComparator implements Comparator<Student>{ @Override public int compare(Student o1, Student o2) { return o1.age-o2.age; } } //Different classes of the same package public class NameComparator implements Comparator<Student> { @Override public int compare(Student o1, Student o2) { return o1.name.compareTo(o2.name); } } //main program public static void main(String[] args) { Student[] student = new Student[3]; student[0] = new Student("caocao",18); student[1] = new Student("liubei",26); student[2] = new Student("sunquan",22); NameComparator nameComparator = new NameComparator(); Arrays.sort(student,nameComparator); System.out.println(Arrays.toString(student)); }
It is more convenient to use a comparator. You can implement a comparator yourself if you want to use any comparison.
Compared with Comparable, once a comparison method is written to death, it cannot be easily modified
3. Clonable interface
Cloneable interface is an empty interface (identification interface), which just means that this class can be cloned.
class Student1 implements Cloneable{ //This interface represents that the class can be cloned public String name; public int age; public Student1(String name,int age){ this.name = name; this.age = age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } //clone in Override Methods @Override protected Object clone() throws CloneNotSupportedException { //There is no clone method in the interface, so you need to override the Object method Student1 student1 = (Student1) super.clone(); //Calling the cloning method of the parent class gave Student1 return student1; } } public class testDome1 { public static void main(String[] args) throws CloneNotSupportedException { Student1 student1 = new Student1("caocao",18); Student1 student2 = (Student1)student1.clone(); System.out.println(student1); System.out.println(student2); } }
Deep and shallow copy problems in clonable:
Shallow copy
class Part implements Cloneable{ public int m = 10; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } } class Student1 implements Cloneable{ //This interface represents that the class can be cloned public String name; public int age; public Part a; public Student1(String name,int age){ this.name = name; this.age = age; this.a = new Part(); } @Override public String toString() { return "Student1{" + "name='" + name + '\'' + ", age=" + age + ", a=" + a + '}'; } //clone in Override Methods @Override protected Object clone() throws CloneNotSupportedException { //There is no clone method in the interface, so you need to override the Object method Student1 student1 = (Student1) super.clone(); //Calling the cloning method of the parent class gave Student1 student1.a = (Part)this.a.clone(); return student1; } } public class testDome1 { public static void main(String[] args) throws CloneNotSupportedException { Student1 student1 = new Student1("caocao",18); Student1 student2 = (Student1)student1.clone(); System.out.println(student1); System.out.println(student2); } }
The above method is to change the shallow copy to the deep copy