Java object-oriented programming, package, inheritance, composition, polymorphism, abstract class, interface

Understand java object-oriented programming and basic syntax

1. Package

Package is a way to organize classes. The main purpose of using package is to ensure the uniqueness of classes
import
Import classes in package

import java.util.Date;
public class Test {
    public static void main(String[] args) {
        Date date = new Date();
        // Get a millisecond timestamp
        System.out.println(date.getTime());
   }
}

If you need to use other classes in java.util, you can use import java.util*

import java.util.*;
public class Test {
    public static void main(String[] args) {
        Date date = new Date();
        // Get a millisecond timestamp
        System.out.println(date.getTime());
   }
}

However, we prefer to explicitly specify the class name to be imported. Otherwise, conflicts are likely to occur
For example, the class java.sql.Date in java.sql and the class java.util.Date in java.util

import java.util.*;
import java.sql.*;
public class Test {
    public static void main(String[] args) {
        // There is a class such as Date in util and sql. At this time, ambiguity will occur and compilation error will occur
        Date date = new Date();
        System.out.println(date.getTime());
   }
}

In this way, the compilation fails and the Date is ambiguous. should:

import java.util.*;
import java.sql.*;
public class Test {
    public static void main(String[] args) {
        java.util.Date date = new java.util.Date();
        System.out.println(date.getTime());
   }
}

Use import static to import static methods and fields in the package

import static java.lang.Math.*;
public class Test {
    public static void main(String[] args) {
        double x = 30;
        double y = 40;
        // Static import is more convenient to write 
        // double result = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
        double result = sqrt(pow(x, 2) + pow(y, 2));
        System.out.println(result);
   }
}

Basic rules for putting classes in packages

  1. Add a package statement at the top of the file to specify which package the code is in
  2. The package name needs to be specified as a unique name as far as possible, usually in the inverted form of the company's domain name (e.g. com.cqupt.demo1
  3. The package name should match the code path. For example, if you create a package of com.cqupt.demo1, there will be a corresponding path com/cqupt/demo1 to store the code
  4. If a class does not have a package statement, the class is placed in a default package

2. Access control of package

We have learned about public and private in the class. Members in private can only be used inside the class
If a member does not contain public and private keywords, this member can be used in other classes inside the package, but not in classes outside the package. (package access permission)

3. Succession


Syntax:

class Subclass extends Parent class { 
 
} 
class Animal {
    public String name;
    public int age;
    private int count;

    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }

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

class Dog extends Animal {
    public Dog(String name, int age) {
        super(name, age);
    }
}

class Bird extends Animal {
    public Bird(String name, int age,String swing) {
        super(name, age);
        this.swing=swing;
    }

    public String swing;

    public void fly() {
        System.out.println(name + "fly()"+swing);
    }
}

public class TestDemo {
    public static void main(String[] args) {
        Animal animal=new Dog("jenny",23);//The parent class references the child class object

    }
    public static void main1(String[] args) {
        Dog dog = new Dog("jenny",22);
        System.out.println(dog.name);
        dog.eat();

        Bird bird = new Bird("james",45,"Cover by Aami ");
        System.out.println(bird.name);
        bird.eat();
        bird.fly();
    }

}

1. Use extends to specify the parent class
2. A subclass in Java can only inherit one parent class (while languages such as C++/Python support multiple inheritance)
3. The subclass will inherit all public fields and methods of the parent class
4. The private fields and methods of the parent class cannot be accessed in the child class
5. Instances of subclasses also contain instances of parent classes. You can use the super keyword to get references to instances of parent classes

4.protected keyword

Just now, we found that if the field is set to private, the subclass cannot be accessed. However, setting it to public violates our original intention of "encapsulation"
The best of both worlds is the protected keyword:
The fields and methods modified by protected are inaccessible to the caller of the class
For subclasses of classes and other classes in the same package, the fields and methods modified by protected are accessible

Summary: there are four access permissions for fields and methods in Java

  1. private: it can be accessed inside the class, but not outside the class
  2. Default (also called package access permission): it can be accessed inside a class. Classes in the same package can be accessed, but other classes cannot
  3. protected: it can be accessed inside a class. Subclasses and classes in the same package can be accessed. Other classes cannot be accessed
  4. public: both inside the class and the caller of the class can access it

5.final keyword

6. Combination

Similar to inheritance, composition is also a way to express the relationship between classes and achieve the effect of code reuse.

Combinatorial representation has - a semantics
A school "contains" several students and teachers.

public class Student { 
 ... 
} 
public class Teacher { 
 ... 
} 
public class School { 
 public Student[] students; 
 public Teacher[] teachers; 
} 

7. Polymorphism

What are the benefits of using polymorphism?

  1. The cost of using classes by class callers is further reduced
    Encapsulation means that the caller of a class does not need to know the implementation details of the class
    Polymorphism allows the caller of a class not to know the type of the class, but to know that the object has a method
    Therefore, polymorphism can be understood as a further encapsulation, which further reduces the use cost of class callers
  2. It can reduce the "loop complexity" of the code and avoid using a lot of if - else
  3. More scalable

7.1 upward transformation

public static void main1(String[] args) {
        //Upward transformation
        Animal animal = new Dog("jenny", 23);//The parent class references the child class object
        Dog dog = new Dog("james", 55);
        func(dog);
    }

At this time, animal is a reference to a parent class (Animal) and points to an instance of a subclass (Dog). This writing is called upward transformation

7.2 dynamic binding

//Dynamic binding
public static void main2(String[] args) {
    Animal animal = new Dog("jenny", 23);//The parent class references the child class object
    animal.eat();

    Animal animal2 = new Bird("jjj", 45, "ijh");
    animal2.eat();
    //Only the members of the parent class can be accessed through the reference of the parent class
    System.out.println(animal2.name);
}

In Java, which code (which is the code of the parent class method or the code of the subclass method) is executed by calling the method of a class, depends on whether the reference refers to the parent object or the subclass object. This procedure is decided by the program runtime (instead of the compile period), so it is called dynamic binding.

7.3 method rewriting

The subclass implements the method with the same name as the parent class, and the type and number of parameters are exactly the same. This is called override

be careful:

  1. Rewriting and overloading are completely different. Don't confuse (think about it, what are the rules of overloading?)
  2. Ordinary methods can be overridden, but static methods modified by static cannot be overridden
  3. Overriding a subclass's method cannot have lower access than the parent's method
  4. The return value type of the overridden method may not be the same as that of the parent class (but it is recommended to write it the same, except in special cases)
class Animal {
    public String name;
    public int age;
    private int count;

    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void eat() {
        System.out.println(name + "eat()");
    }
}

class Dog extends Animal {
    public Dog(String name, int age) {
        super(name, age);
    }

    @Override
    public void eat() {
        System.out.println(name + " Gobbling eat()");
    }

    //heavy load
    public void func(int a) {
        System.out.println(a);
    }

    public void func(int a, int b) {
        System.out.println(a + b);
    }

    public void func(int a, int b, double n) {
        System.out.println(a + b + n);
    }

}

class Bird extends Animal {
    public Bird(String name, int age, String swing) {
        super(name, age);
        this.swing = swing;
    }

    public String swing;

    public void fly() {
        System.out.println(name + "fly()" + swing);
    }
}

The Dog class overrides the eat() method in the parent class Animal

7.4 downward transformation

Upward transformation means that a child object is transformed into a parent object. Downward transformation means that a parent object is transformed into a child object. Compared with upward transformation, downward transformation is less common and not very safe

7.5 static binding

//heavy load
    public void func(int a) {
        System.out.println(a);
    }
    public void func(int a, int b) {
        System.out.println(a + b);
    }
    public void func(int a, int b, double n) {
        System.out.println(a + b + n);
    }
 //Static binding
    public static void main3(String[] args) {
        Dog dog = new Dog("jenny", 34);
        dog.func(3);
        dog.func(2, 4);
        dog.func(4, 5, 3.88);
    }

7.6 super keyword

In the previous code, due to the rewriting mechanism, the methods of the subclass are called. What if you need to call the parent method inside the subclass? You can use the super keyword

7.7 call the method of rewriting in a construction method (a pit).

We create two classes, B is the parent class, D is a subclass. D rewrites the func method, and calls func in the construction method of B:

class B { 
 public B() { 
 // do nothing 
 func(); 
 } 
 public void func() { 
 System.out.println("B.func()"); 
 } 
} 
class D extends B { 
 private int num = 1; 
 @Override 
 public void func() { 
 System.out.println("D.func() " + num); 
 } 
} 
public class Test { 
 public static void main(String[] args) { 
 D d = new D(); 
  } 
}

//Run result: D.func()0
1. While constructing D object, the construction method of B will be called
2., the func method is called in the construction method of B, which triggers dynamic binding and calls to func in D.
3. At this time, the D object itself has not been constructed. At this time, num is in the uninitialized state, and the value is 0

Keywords: Java Back-end JavaSE

Added by robert.access on Wed, 10 Nov 2021 18:30:05 +0200