java object-oriented -- package + inheritance + polymorphism

Keywords: Java Back-end Programmer

package

Concept:

It is a way to organize classes, which can ensure the uniqueness of classes

create package


Click new under src package and then package to create a package. Creating a new java class under the created package will create a class.

matters needing attention:

1. Add a package statement at the top of the file to specify which package the code is in. For example, create a class package. For the new java file under this package, add package class at the top (IDEA is usually generated automatically)
2 if a class does not have a package statement, the class is placed in a default package
3. The package name should be specified as a unique name as far as possible

Import classes in package:

Direct import

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

For this import, we need to know that the class we call is in the package directory, and it's troublesome. We can understand it here.

import statementimport

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

When we instantiate the Date class, we can find that the IDEA will automatically prompt the package of the class. At this time, we just need to double-click java.util (it should be mentioned here that the class names in different packages can be the same. The timestamp function in our statements is implemented in the Date class under the java.util package. This problem does not need to be studied in depth, but only needs to understand how to import the classes in the package using import). At this time, it will automatically help us import the classes in the package.
The above is to import the specific class name in the package through the import statement. In fact, java.util. * can also be used; the code will not report an error when importing

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

This can be understood as a general configuration item, which is really convenient and simple. However, we do not recommend importing classes in the package in this way. It is best to be specific to the class name

import java.util.*;
import java.sql.*;

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

If you import java.util and java.sql packages at this time, the Date will report an error. The reason is that there is a Date class under both util and SQL packages. At this time, the compiler is confused and does not know whose class is imported. At this time, we need to import a specific class name to avoid reporting an error

matters needing attention:

1 different from c language, java does not import all classes under the package when using generic configuration items. It only uses which class it needs, while c language imports all classes
2 the package name must be lowercase
3 when importing the classes in the package, you should import specific class names and develop good programming habits.

Static import (just understand)

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

import static java.lang.System.*;
import static java.lang.Math.*;
public class testdemo {
    public static  void main(String[] args) {
       Date date=new Date();
        // Get a millisecond timestamp
        out.println(date.getTime());
        out.println(max(2,3));
    }
}

When taking the maximum value, if static import is not called, it must be math.max(2,3). You can see that system and math can be omitted, which is static import.

Access rights for packages

In java classes and objects, we have preliminarily recognized the public and priate access qualifiers in classes. Package access permission is to directly define its type without any keyword modification. Access scope: it can only be in the same package.

Common system packages

  1. java.lang: system common basic classes (String, Object). This package is automatically imported from JDK1.1.
  2. java.lang.reflect:java reflection programming package;
  3. java.net: network programming development package.
  4. java.sql: support package for database development.
  5. java.util: it is a tool package provided by java. (collection class, etc.) is very important
  6. java.io:I/O programming development kit.

inherit

class dog{
    public String name;
    public int age;
    public void eat(){
        System.out.println("eat()");
    }
}
class bird{
    public String name;
    public int age;
    public void eat(){
        System.out.println("eat()");
    }
    public void fly(){
        System.out.println("fly()");
    }
}
public class test {
    public static void main(String[] args) {
    dog dog=new dog();
    dog.name="haha";
    bird bird=new bird();
    bird.name="heihei";
    bird.fly();
    }
}

In the above code, we can see that both bird and dog classes contain common fields and methods. At this time, we can reuse the code through inheritance (extract the common attributes of the code)

class animal{
    public String name;
    public int age;
    public void eat(){
        System.out.println("eat()");
    }
}
class dog extends animal{
}
class bird extends animal{
    public void fly(){
        System.out.println("fly()");
    }
}
public class test {
    public static void main(String[] args) {
    dog dog=new dog();
    dog.name="haha";
    bird bird=new bird();
    bird.name="heihei";
    bird.fly();
    }
}

Here we can find that inheritance is derived from the keyword extends, in which dog and bird are called subclasses, derived classes, and animal are called parent classes, base classes, and superclasses

Inherited syntax rules

Class subclass extends parent class{
}

Key points:

1 specify the parent class through the keyword extends
2. Only one parent class can be inherited in Java
3. The subclass will inherit all fields and methods in the parent class
4 for the field decorated with private, subclasses cannot be accessed
5 subclass instances also contain instances of the parent class. You can use the super keyword to get a reference to the parent class instance
If a class does not want to be inherited, you can use the keyword final to modify the class

super keyword (key)

1 super() helps the parent class to construct

When using the construction method to construct a subclass, you must first help the parent class to construct

class animal{
    public String name;
    public int age;
    public void eat(){
        System.out.println(name+"eat()"+age);
    }
    public animal(String name,int age){
      this.name=name;
      this.age=age;
      eat();
    }
    public void func(){
        System.out.println("");
    }
}
class dog extends animal{
    public dog(String name,int age){
        super(name,age);//Call the constructor whose parent class contains two parameters
    }
}
class bird extends animal{
    public bird(String name,int age){
        super(name,age);//Call the constructor whose parent class contains two parameters
    }
    public void fly(){
        System.out.println("fly()");
    }
}
public class test {
    public static void main(String[] args) {
    dog dog=new dog("haha",10);
    bird bird=new bird("heihei",20);
    }
}

matters needing attention:

1 super () must be in the first line of the subclass construction method when helping a subclass construct a parent class
2 super refers to the instance reference of the parent class, which depends on the object, so it cannot appear in the static method

2. Super. Func() calls the normal method of the parent class

class animal{
    public String name;
    public int age;
    public void eat(){
        System.out.println(name+"eat()"+age);
    }
    public animal(String name,int age){
        this.name=name;
        this.age=age;
    }
    public void func(){
        System.out.println("");
    }
}
class dog extends animal{
    public dog(String name,int age){
        super(name,age);
        super.eat();
    }
}

In this code, we can see that the super keyword can be used to call the ordinary methods of the parent class in the subclass. Here, we should note that super cannot write out the outside of the method when calling the methods of the parent class

3 super.data refers to the parent class instance

This is to access the fields of the parent class through the super keyword in the subclass

The difference between super keyword and this keyword:

1. Super is used in subclasses on the premise of parent-child classes. To access the methods and fields of the parent class in the subclass, and to help the parent class construct methods first, it must be placed in the first line
2. If the search scope of this keyword is in this class or if it is not in this class, you can search in the parent class. Through this, you can call the fields in this class (if it is not in this class, you will search in the parent class), call the methods in this class (if it is not in this class, you will search in the parent class), or call the construction method in this class. Calling the construction method needs to be placed in the first line of the method

protected keyword (key)

1 in the same class

public class time {
    protected int val = 99;

    public static void main(String[] args) {
        time time=new time();
        System.out.println(time.val);
    }
}

At this time, the code can execute normally

2 in different classes in the same package


You can see that test and time are different classes under the same package, and test can access the protected modified val

3 subclasses under different packages



Under different packages, we need to import the parent class into the subclass and inherit. Because it is a parent-child relationship, we need to use the super keyword to access the instances in the parent class (the super keyword cannot appear in static methods, because super is a reference to the parent object and depends on the object, while static methods belong to classes and do not depend on the object)

4 non subclasses under different packages


Obviously, this is not accessible

Summary of access rights

Combined with the public, private, and package access rights we talked about before, and the protected we have learned now, let's make a summary
private: it can only be used inside the class and cannot be accessed outside
public: the external and internal of a class can be accessed under the same package or different packages
default (package access permission): can only be accessed in the same package
protected: the same package, the same class, and the parent and child classes of different packages can be accessed. The super keyword should be used for access in the parent and child classes. Non child classes of different packages cannot be accessed

More complex inheritance relationships: (understand)

Among the animals we just cited, cats are also divided into many kinds, such as domestic cat species and foreign cat species. Domestic cat species can be divided into those kinds, which can be further subdivided. This inheritance relationship must have a logical connection, not just for inheritance. Generally speaking, we'd better not exceed 3 layers for this complex inheritance relationship

Polymorphism:

Upward transformation (key)


See the following code for details

bird bird=new bird("heihei",20);

In the above example, we know that bird is a reference to bird, which can be written in the following form

bird bird=new bird("heihei",20);
animal bird2 = bird;
//Or write it like this
animal bird2 = new bird("heihei",20);

At this time, this method is called upward transformation, that is, the reference of the parent class refers to the object of the child class.

Timing of upward Transformation:

1 direct assignment method
This method is actually the example we just introduced when introducing the upward transformation.
2 as the return value

  public static void main(String[] args) {
        animal animal=func();
    }
    public static animal func(){
        bird bird=new bird("gas",39);
        return bird;
    }

3 parameters of the method

   public static void main(String[] args) {
        bird bird =new bird("aio",39);
        func(bird);
    }
    public static void func(animal animal){
       animal.eat();
    }

Dynamic binding (key)

Conditions for occurrence:

1 an upward transformation has occurred (the parent class references the object of the child class)
2. Call the override method with the same name of the parent class and the child class through the reference of the parent class
Dynamic binding is also called runtime polymorphism (as for what is polymorphism, it will be described in detail below), that is, it is determined that the eat method of the subclass is called at runtime

class animal{
    public String name;
    public int age;
    public void eat(){
        System.out.println(name+"eat()"+age);
    }
    public animal(String name,int age){
        this.name=name;
        this.age=age;
    }
}
class bird extends animal{
    public bird(String name,int age){
        super(name,age);
    }
    @Override
    public void eat() {
        System.out.println(name+"eat");
    }
    public void fly(){
        System.out.println("fly()");
    }
}
public class blos {
    public static void main(String[] args) {
        animal animal=new bird("hsd",34);
        animal.eat();
    }
}

We can start with the main function. We can see that the eat method in the parent class is not executed when animal calls the eat method. Instead, we call the eat method with the same name, the same parameters and the same return value in the subclass. At this time, we say that dynamic binding has occurred, and the eat method is also called the overwrite method. In this process, we say that eat has been rewritten and can be overridden To label with @ override

Static binding:

Unlike dynamic binding, static binding determines that the eat method of the subclass is called at compile time

public class blos {
    public static void main(String[] args) {
        duck duck=new duck();
        duck.fun("haha");
    }
}
class duck{
    public void fun(){
        System.out.println("No parameter");
    }
    public void fun(String name){
        System.out.println("One parameter");
    }
    public void fun(String name,int age){
        System.out.println("Two parameters");
    }
}

When duck calls the fun method, it passes several parameters to fun to call that method. At this time, we say that static binding occurs. You can know that static binding needs to occur under overload, while dynamic binding needs to be rewritten first.

Considerations for rewriting

1. The method modified by final cannot be overridden
2 methods modified by private cannot be overridden
3 methods modified by static cannot be overridden
4. The modifier qualifier of the subclass method is greater than that of the parent class

The difference between rewriting and overloading

1. The return value of rewriting should be the same (there is a special case here, that is, it can be covariant type). Overloading is independent of the return value
2 override and overloaded method names should be the same
3. The rewritten method parameters should be consistent, and the overloaded method parameters should be different (the method parameters here include the type and number of parameters)

Conclusion:

In a later article, we will continue to explain in detail what is polymorphism, what is abstract class and what is interface. I hope this article can be helpful to you!

Posted by hiberphoptik on Fri, 19 Nov 2021 05:25:26 -0800