Secrets of JAVA Training Chapter 7: Object-Oriented Programming

Keywords: Java OOP JavaSE

Expiration:
Secrets of JAVA Training Chapter 1: Pain
Secrets of JAVA Training Chapter II: Gradually Magic
Secrets of JAVA Training Chapter III: Jedi Strike Back
Secrets of JAVA Training Chapter IV: Closed-door Training
Secrets of JAVA Training Chapter V: "Wage and Gallbladder"
Secrets of JAVA Training Chapter VI: Battle
JAVA Refinement Secret Books (Pan Wai Paper) Chapter 1: Do you really know these four code titles?

Life kisses me with pain, but I return it with song.

Foreword: What is object-oriented programming

In the previous chapters, we introduced what is object-oriented and learned the difference between object-oriented and process-oriented. Let's review what is object-oriented and what is process-oriented again, this time without an example.

Understanding what is object-oriented, let's look at how to do object-oriented programming, which is explained in more detail below.

1. Package

Introduction 1: Organize similar or related classes or interfaces into a package for easy searching.
Introduction 2: Two classes in the same package cannot have the same name. Classes in different packages can have the same name.

(For example, Zhang San has an older son named Wang Dali, so he can't name his second son or Wang Dali. But the son of the five next-door Kings can call Wang Dali, because they are two families, and you can't care what their son calls. You have the same name as a stranger. Most people have it).

1. Importing classes in packages

java provides us with classes that have been written by developers for us to use. For example:

import java.util.Scanner;

With the code above, we refer to the Scanner class in the java.util package, and then we can use it. If you want to use another class in util, we can do so, which saves a lot of time. (JAVA doesn't increase the extra space requirements by importing a package and using only one of the classes, it introduces that class and uses that class instead.)

import java.util.*

There are many more classes that can be directly introduced and pasted with a piece of software.
You can find it here.

What if the code below appears.


There is a Date class in both the util and sql packages, and an error will occur when compiling. The system does not know that you are the Date class in the package you are referencing. In this case, use the full class name.

2. How classes fit into packages

  1. Add a package statement at the top of the file to specify which package the code is in.
package com.zhanghao;

public class project {
    public static void main(String[] args) {
        System.out.println();
    }
}

  1. Package names should be as unique as possible. Do not duplicate the phenomenon of package names. Generally, the company's domain name is reversed. Individuals can reverse their own names: zhanghao.com - > com.zhanghao.
  2. The package name must match the code path.For example, if you create a package of com.zhanghao, there will be a corresponding path, com/zhanghao, to store the code.
  3. If there is no package statement at the top of a class, the class is placed in a default package.

Creation steps:

A window will pop up to let you enter the package name.
This package will be created on the left side

Create Class

Once the class name is entered, the class is created successfully and a package statement is automatically formed at the top.

2. Inheritance

1. What is inheritance

Inheritance is a method that allows an object of one type to acquire the properties of another type of object. It supports the concept of hierarchical classification. Inheritance is the ability to use all the functions of an existing class and extend those functions without rewriting the original class. New classes created by inheritance are called subclasses or derived classes.Inherited classes are called "base classes", "parent classes" or "superclasses". The process of inheritance is from general to special. To achieve inheritance, the properties and methods of the parent class can be realized through "inheritance" and "combination" without the need for additional encoding. Interface inheritance refers to the ability to implement only using the names of the properties and methods, but the subclasses must provide the ability to do so.
Knowing what inheritance is, we'll impress you with the code and pictures below.

The code in the picture is not clear, so the source code is copied below.

package com.zhanghao;

class Animal{//Create this class of animals
    public String name;//Animals have names
    public int age;//Aged
    public Animal(String name,int age) {//Construction method
        this.name=name;
        this.age=age;
    }
    public void eat(){//Animals eat this, and we write a way
        System.out.println(age+"Aged"+name+"I am eating");
    }
    public void run(){//Animals run, we write a method
        System.out.println(age+"Aged"+name+"Running");
    }
}
class Sheep{//Create the sheep class
    public String name;//Sheep has a name
    public int age;//Sheep are old
    public Sheep(String name,int age){
        this.name=name;
        this.age=age;
    }
    public void eat(){//Sheep eat this behavior, we write a method
        System.out.println(age+"Aged"+name+"I am eating");
    }
    public void run(){//Sheep run, we write a method
        System.out.println(age+"Aged"+name+"Running");
    }
}
class Tiger{
    public String name;//Tiger has a name
    public int age;//Tiger has age
    public Tiger(String name,int age){
        this.name=name;
        this.age=age;
    }
    public void eat(){//The tiger eats this, so let's write a way
        System.out.println(age+"Aged"+name+"I am eating");
    }
    public void run(){//The tiger has run behavior, we write a method
        System.out.println(age+"Aged"+name+"Running");
    }
}
public class project {
    public static void main(String[] args) {
        Tiger tiger=new Tiger("Tiger Overlord",20);
        tiger.eat();
        tiger.run();
    }

    public static void main2(String[] args) {
        Sheep sheep=new Sheep("Shawn",5);
        sheep.eat();
        sheep.run();
    }

    public static void main1(String[] args) {
        Animal animal=new Animal("Animal",4);//Instantiate Object
        animal.eat();//Make animals move
        animal.run();
    }
}
  1. From the code and picture above, we can see that there are many duplicate codes, even the same code, the attributes and methods in these three classes are identical, and the behavior and meaning are always the same.
  2. We can then use inheritance because both tigers and sheep belong to animals. Let both tigers and sheep inherit from animals.


3.This change in the code greatly reduces the repetition and clarity of the code.

package com.zhanghao;
class Animal{//Create this class of animals
    public String name;
    public int age;
    public Animal(String name,int age) {//Construction method
        this.name=name;
        this.age=age;
    }
    public void eat(){
        System.out.println(age+"Aged"+name+"I am eating");
    }
    public void run(){
        System.out.println(age+"Aged"+name+"Running");
    }
}
class Sheep extends Animal{//Create the sheep class
    public Sheep(String name,int age) {
        super(name, age);
    }
}
class Tiger extends Animal{
    public Tiger(String name,int age){
        super(name,age);
    }
    public void bite(){
        System.out.println(this.name+"Biting");
    }
}
public class project {
    public static void main(String[] args) {
        Tiger tiger=new Tiger("Tiger Overlord",20);
        tiger.eat();
        tiger.run();
        tiger.bite();
        Sheep sheep=new Sheep("Shawn",5);
        sheep.run();
        sheep.eat();
    }
}
  1. Use the keyword extends to achieve inheritance: class subclass extends parent class
  2. A child in JAVA can have only one parent, that is, a child can have only one father, but a father can have several children.
  3. All children can inherit the parent's public properties and methods, just like genes, children can inherit father's genes, just like looks and height.
  4. But the methods and attributes of private s in the parent are inaccessible in the children, that is, Dad is in luck, and the son is not able to use Dad's luck to do his own things.
  5. Instances of subclasses also contain instances of the parent class, which can be referenced using the super keyword.
  6. Extds originally means "extension". The inheritance of the class we write can also be interpreted as "extension" in code based on the parent class. For example, the Tiger class we write extends the fly method on the basis of Animal.
  7. The inherited subclasses can also derive new subclasses, such as tigers inheriting from animals, tigers can also derive Siberian tigers, white tigers, Bengali tigers, etc. Siberian tigers can also derive adult tigers, pups, queens, etc.
  8. There are many levels, can you really remember, so avoid too many levels of inheritance in programming, generally no more than three levels.

3. Packaging

Encapsulation has four access rights to properties and methods.

  1. private - private
  2. default -"default
  3. protected--protected
  4. public--public

These four levels of access can be understood as:
public > protected > default > private.
There is a classic table to better understand.

This is where they can be used. When and what access rights to methods or attributes are required, they need to be set up by the programmer himself, using stricter access rights whenever possible.

final can also modify classes:
The final-modified class representation cannot be inherited, and the function of the final keyword is to restrict the class from being inherited
"Restriction" means "inflexibility".Flexibility is not always a good thing in programming.Flexibility may mean more error prone. When a class decorated with final is inherited, errors are compiled, suggesting that such inheritance is contrary to the original intent of the class design.

4. Combination

  1. In one class, objects of another class are used as data attributes, called combinations of classes.
  2. When there is a significant difference between classes, and smaller classes are the components required by larger classes, composition is better.
  3. For example, when a class is doctor, a class is nurse and there are some similar classes, they can be combined into a hospital class. Their relationship is a has-a relationship, that is, a hospital has-a doctor, a hospital has-a nurse, and so on.
  4. Inheritance is the relationship between is-a, such as the subclass is-a parent, the tiger is-a animal, the sheep is-a animal, and so on.

V. Polymorphism

1. What is polymorphism

This means that objects with different internal structures can share the same external interface. This means that although the specific operations for different objects are different, they can be called in the same way through a common class.

2. Upward Transition

We implemented the inherited operation with the code above.

Tiger tiger=new Tiger("Tiger Overlord",20);

This code can also be written in the form below.

Animal animal=new Tiger("Tiger Overlord",20);
  1. At this point animal is a reference to an Animal that points to an instance of Tiger.This is called the upward transition.
  2. This upward transition occurs with direct assignment.
  3. There will be an upward transition in method communication.
public class project {
    public static void main(String[] args) {
        Tiger tiger=new Tiger("Tiger Overlord",20);
        feed(tiger);
    }
    public static void feed(Animal animal){
        animal.eat("Pheasant");
    }
}
  1. There will also be an upward transition from method return.
public class project {
    public static void main(String[] args) {
        Animal animal=getname();
    }
    public static Animal getname(){
        Tiger tiger=new Tiger("Tiger Overlord",20);
        return tiger;
    }
}

3. Dynamic Binding

If we add an eat method to the subclass Tiger at this time, will we call the eat method in the subclass or the eat method in the parent class when we call the eat method again?

class Animal{//Create this class of animals
    public String name;
    public Animal(String name) {//Construction method
        this.name = name;
    }
    public void eat(String food){
        System.out.println("Animal Action");
        System.out.println(name+"I am eating"+food);
    }
}
class Sheep extends Animal{//Create the sheep class
    public Sheep(String name) {
        super(name);
    }
    public void eat(String food){
        System.out.println("Action of Sheep");
        System.out.println(name+"I am eating"+food);
    }
}
public class project {
    public static void main(String[] args) {
        Animal animal=new Animal("Animal");
        animal.eat("meat");
        Animal animal1=new Sheep("sheep");
        animal1.eat("grass");
    }

}

Output result after execution.

At this point, we can see who calls who, who references who, although both are Animal-type references, when we call eat function, we call it according to the instance we point to, depending on which one we call
Use to point to parent or child objects.This process is determined by the program runtime (not compile time), and is therefore called dynamic binding

4. Method Rewrite

  1. In the last paragraph we actually used the function of overwriting, which can also be called overwriting, overwriting.
  2. The parent class in the previous paragraph has a eat method, and the child class has a eat method with the same return value parameter, which is an override.
  3. Rewrite and overload are completely different, and their two rules are completely incompatible. The requirements for overload are discussed in the previous chapters.
  4. Common methods can be overridden, while static methods modified by static cannot.
  5. Methods that override subclasses cannot have lower access than methods of parent classes.
  6. Overridden methods do not necessarily have the same return value type as parent methods (but it is recommended that they be written the same, except in special cases)

public > protected > default > private.
Remember this range of use.
Assume:

class Animal{//Create this class of animals
    public String name;
    public Animal(String name) {//Construction method
        this.name = name;
    }
    public void eat(String food){
        System.out.println("Animal Action");
        System.out.println(name+"I am eating"+food);
    }
}
class Sheep extends Animal{//Create the sheep class
    public Sheep(String name) {
        super(name);
    }
    private void eat(String food){
        System.out.println("Action of Sheep");
        System.out.println(name+"I am eating"+food);
    }
}

There will be compilation errors in the code, that is, when a subclass overrides a parent class's method, the subclass's method cannot be used less widely than the parent's method.

We can add'@Override'to the overridden method so that if there are some writing errors in the method, the code will compile errors to remind us that the override cannot be made.

5. Understanding polymorphism

What are polymorphisms? As we have described above, we can now use rewriting, dynamic binding, and so on to design programs that use polymorphisms.

  1. In this case, we can write the code above the project class by the implementer of the class and below the splitter line by the caller of the class.
  2. When the caller of the class writes the conduct method, the parameter type is Animal (parent class).
  3. At this point, you do not know within the method, nor do you care what type of instance the current food reference is pointing to.
  4. At this point, food, a reference to the eat method, may behave differently, depending on the instance corresponding to the food. This behavior is called polymorphism.

There is a story in the Chinese version of Head First java that lets you know the benefits of object-oriented programming and why you use it.




6. Downward Transition

Sometimes we also use downward transformation, but it is not common to upgrade, downward transformation into parent object into child object, upward transformation is understandable, this is also very understanding.

Animal animal=new Tiger("Tiger Overlord",20);
animal.eat();

The above code cannot be compiled and should be cast.

Animal animal=new Tiger("Tiger Overlord",20);
Tiger tiger=(Tiger) animal;

There are risks associated with downward transition and caution is required.

7.super keyword

This keyword was previously used in our method rewrite code, but what this keyword does is not explained. Now let's talk about it separately

  1. Use super to call the constructor of the parent class.
class Sheep extends Animal{//Create the sheep class
   public Sheep(String name) {
        super(name);
   }
}
  1. Use super to invoke the common method of the parent class
class Tiger extends Animal{
    public Tiger(String name){
        super(name);
    }
    @Override
    public void eat(String food){
        super.eat(food);
        System.out.println(this.name+"Biting");
    }
}

In this code, if eat is called directly (without super) in the eatmethod of the subclass, then it is considered to be calling the subclass's own eat (that is, recursive). The super keyword is added to the method of calling the parent class

The difference between super and this:

  1. super() is primarily a call to a parent constructor, and this() is a call to an overloaded constructor
  2. super() is used primarily in constructors that inherit subclasses of the parent class and in different classes; this() is used primarily in different constructors of the same class

Same:

  1. Both super() and this() must be called on the first line of the constructor, otherwise it is an error

If the following code conditions occur, they are not related to super:

class Animal{//Create this class of animals
    public String name;
    public Animal() {//Construction method
        run();
    }
    public void run(){
        System.out.println("Animal");
    }
}
class Tiger extends Animal{
    private int sum=1;
    @Override
    public void run(){
        System.out.println("tiger "+sum);
    }
}
public class project {
    public static void main(String[] args) {
        Tiger tiger=new Tiger();
    }
}

The output is:

Reason:
"Make the object work in the simplest way possible". Try not to call a method in the constructor (dynamic binding is triggered if the method is overridden by a subclass, but the subclass object is not yet constructed), there may be some hidden but extremely difficult problems to find

6. Abstract Classes

  1. Without a working method, we can design it as an abstract method. Classes that contain abstract methods are called abstract classes.
  2. The abstract keyword precedes the method to indicate that it is an abstract method. At the same time, the abstract method has no method body (no {}, no specific code can be executed)
  3. For a class that contains an abstract method, the abstract keyword must be added to indicate that it is an abstract class
  4. Abstract classes cannot be instantiated directly (error examples below).
abstract class Tiger{
    abstract public void  run();
}
public class project {
    public static void main(String[] args) {
        Tiger tiger=new Tiger();
    }
}
  1. An abstract method cannot be private (error demonstration below).
abstract class Tiger{
    abstract private void  run();
}
  1. An abstract class can contain other non-abstract methods as well as fields. This non-abstract method has the same rules as a normal method and can be overridden or called directly by a subclass. (The output of the code below is food).
abstract class Animal{
    abstract public void run();
    void food(){
        System.out.println("food");
    }

}
class Tiger extends Animal{
    public void run(){
        System.out.println("tiger ");
    }
}
public class project {
    public static void main(String[] args) {
        Animal animal=new Tiger();
        animal.food();
    }
}
  1. The most important function of an abstract class is to be inherited.
  2. An abstract class is a template used to create subclasses in an inheritance hierarchy to capture the common characteristics of subclasses.
  3. There are some methods in the parent class that really don't need to be written, because the methods in the subclasses must be different.
  4. Write as an abstract class, so when you look at the code, you know that it is an abstract method, and that this method is implemented in subclasses, so it is indicative.

7. Interfaces

interface IShape {
    void draw();
}
class Cycle implements IShape {
	public static final int num=10;
    @Override
    public void draw() {
        System.out.println("○");
    }
}
  1. Interfaces in Java are decorated with the interface keyword.
  2. Interfaces can contain variables, methods; variables are specified as public static final by the hermit, and methods are specified as public abstract by the hermit (simplifying the code above).
interface IShape {
	void draw();
	int num = 10;
}
  1. Interfaces cannot be individually instantiated.
  2. Interfaces support multiple inheritance, that is, an interface can extend multiple interfaces, which indirectly solves the single inheritance problem of classes in Java.
  3. A class can implement multiple interfaces;
  4. The implementation class of an interface can only be instantiated if the method in the interface is implemented.
  5. Interfaces have only definitions, not methods
  6. Interfaces can also inherit from one another, using extends
interface IFlying {
    void fly();
}
interface ISwimming extends IFlying  {
    void swim();
}

Implement multiple interfaces
Sometimes we need to have a class inherit from multiple parent classes at the same time.This is done in some programming languages through multiple inheritance. However, only single inheritance is supported in Java, and only one parent class can be extends.However, multiple interfaces can be implemented at the same time and similar effects can be inherited.

class Animal {
    protected String name;
    public Animal(String name) {
        this.name = name;
    }
}
interface IFlying {
    void fly();
}
interface IRunning {
    void run();
}
interface ISwimming {
    void swim();
}
class Dog extends Animal implements IRunning {
    public Dog(String name) {
        super(name);
    }
    @Override
    public void run() {
        System.out.println(this.name + "Running on four legs");
    }
}
class Fish extends Animal implements ISwimming {
    public Fish(String name) {
        super(name);
    }
    @Override
    public void swim() {
        System.out.println(this.name + "Swimming with tail");
    }
}
class Bird extends Animal implements IFlying {
    public Bird(String name) {
        super(name);
    }
    @Override
    public void fly() {
        System.out.println(this.name + "Flying");
    }
}
class Wildgoose extends Animal implements IRunning, ISwimming, IFlying {
    public Wildgoose(String name) {
        super(name);
    }
    @Override
    public void fly() {
        System.out.println(this.name + "Flying with wings");
    }
    @Override
    public void run() {
        System.out.println(this.name + "Running on both legs");
    }
    @Override
    public void swim() {
        System.out.println(this.name + "Floating in the water");
    }
}

Summary: The code above shows the most common use in Java object-oriented programming: what are the benefits of designing a class that inherits a parent class while implementing multiple interfaces?Keep in mind the benefits of polymorphism and let programmers forget about types.With an interface, the consumer of a class does not have to focus on the specific type, but only on the capabilities of a class.
Concluding remark: Connect more and use object-oriented programming, so that you can exercise your personal abstraction ability, practice more, and practice will make you perfect. Bye, thank you for watching.

Posted by stewart on Mon, 13 Sep 2021 09:48:06 -0700