Object oriented programming (package + inheritance)

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:

  1. super(): call the constructor of the parent class (must be placed on the first line)
  2. super.data: call the member property of the parent class
  3. super.func: call the member method of the parent class

6. Code execution sequence

  1. static {} of parent class
  2. static {} of subclass
  3. Instance code block of parent class {}
  4. Constructor of parent class
  5. Subclass instance code block {}
  6. 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

  1. Using extensions
  2. A subclass in Java can only inherit one parent class
  3. Subclasses inherit all public fields and methods of the parent class
  4. 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:

  1. final to modify the constant, int a = 10;
  2. 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.
  3. 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:

  1. Direct assignment:
Animal animal = new Dog("Zhang San");
  1. 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){

}
  1. 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

  1. Abstract classes can be inherited, dynamically bound and transformed upward.
  2. Abstract classes cannot be instantiated
  3. Methods in abstract classes must be overridden by subclasses
  4. Abstract classes exist in order to be inherited, because they cannot be instantiated
  5. 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.
  6. Abstract methods cannot be private
  7. Can include common methods
  8. Abstract classes cannot be final decorated.

8, Interface

Use the keyword interface to decorate.

1. Interface details

  1. The method in the interface is public abstract by default, and there can be no concrete implementation
  2. Interface cannot be instantiated
  3. The method in the interface defaults to public static final
  4. The direct relationship between class and interface is implements. At this time, all methods in the interface must be overridden.
  5. Interfaces can also be transformed upward - runtime binding (dynamic binding)
  6. Starting from JDK 1.8, the methods in the interface can have specific implementation, but this method must be modified by default.
  7. In Java, a class can implement multiple interfaces.
  8. 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

Keywords: Java

Added by TruckStuff on Sat, 11 Sep 2021 02:03:37 +0300