Java Object Oriented on JavaSE Foundation

1. Java Object Oriented

1.1. What is object-oriented?

OO (Object Oriented) has been studied in the 1980s with new system development model, such as Object Oriented Analysis (OOA), Object Oriented Design (OOD), Object Oriented Programming (OOP).

Everything is an object for language. Objects in the real world are abstractly represented in the programming world. An object represents a specific operation. An object ultimately forms a complete design. These objects can exist independently or inherit from other objects. Objects interact to convey information and to open programs.Hair.

1.2. Concepts of objects

Java is an object-oriented programming language, and object is the core of object-oriented programming. The so-called object is the entity in the real world. Object and entity correspond to each other. That is to say, every entity in the world is an object, which is a specific concept.

  • Objects have properties and behavior
  • Object has a changing state
  • Object is unique
  • Objects are instances of a category
  • Everything is an object, everything in the real world can be treated as an object

1.3. Object-oriented and process-oriented relationships and differences

Object-orientedProcess Oriented
conceptA new process-oriented programming idea, as its name implies, is to think from the perspective of objects. We put multiple functions into different objects reasonably, emphasizing objects with certain functions. Entities with certain functions are called objects. The smallest object-oriented program unit is classes. Object-oriented is more consistent with the general way of thinking and stable.Good qualitative, reusable, easy to develop large software products, good maintainability.An earlier programming idea, as its name implies, was to think from a process perspective, emphasizing the behavior of functions, the execution process of functions, that is, the order in which they were executed. For each function, we use functions (similar to methods) to implement these steps step by step, calling functions in turn when they are used.
  • Process-oriented design:

    The smallest program unit is a function, each function is responsible for completing a certain function to receive input data, the function processes the input data, and then outputs the result data. The whole software system consists of one function, in which the function as the program entry is called the main function, the main function calls other functions in turn, and the common functions can be called from one another.And implement the whole system function.

  • Process-oriented drawbacks:

    In a top-down design pattern, at the design stage, you need to consider which sub-modules each module should be broken down into, each sub-module into smaller sub-modules, and so on, until the module is refined into a function.

  • Process-oriented issues:

    The design is not intuitive enough, inconsistent with human thinking habits, poor adaptability of system software, poor expandability and low maintainability.

The biggest problem with process-oriented is that with the expansion of the system, process-oriented will not be able to cope with, and ultimately lead to the collapse of the system.

1.4, Object-oriented three core features

The object-oriented development mode is more conducive to people's pioneering thinking, facilitating the division of programs in the specific development process, facilitating the division of work and cooperation among programmers, and improving the development efficiency.

The main reason why this development mode makes the programming more perfect and powerful is that object-oriented has three core features: inheritance, encapsulation and polymorphism.

1.4.1, Inheritance

Inheritance is the process of creating new classes from inheritance information obtained from existing classes. Classes that provide inheritance information are called parent classes (superclasses, base classes); classes that receive inheritance information are called subclasses (derived classes). Inheritance gives a certain degree of continuity to changing software systems, and inheritance is also an important means of variability in encapsulators.

Inheritance:

  • A child class has properties and methods that are not private in its parent class
  • Subclasses can use their own properties and methods, that is, they can extend the parent
  • Subclasses can implement parent's methods in their own way
  • Java inheritance is single inheritance, but it can be multiple inheritance. Single inheritance means that a subclass can only inherit one parent class, such as Class B inherits Class A. Class C inherits Class B. So according to the relationship, Class B is the parent class of Class C and Class A is the parent class of Class B. This is a feature of Java inheritance difference and C++ inheritance.
  • Enhanced coupling between classes (inheritance disadvantage, high coupling will cause code to be tightly connected, less independent of code)

Inheritance in life:

Rabbits and sheep are herbivores, lions and tigers are carnivores.
Herbivores and carnivores are also animals.

As you can see from the diagram above, inheritance means that a child class inherits the characteristics and behavior of the parent class, so that the child class object (instance) has instances and methods of the parent class, or that the child inherits methods from the parent class, so that the child class has the same methods as the parent class.

So the relationships that inheritance relationships need to conform to are-a, the parent class is more generic, and the child class is more specific.

Although both practical and carnivorous animals belong to animals, their attributes and behavior are different, so the subclasses will have the general characteristics of the parent and will have some unique characteristics of their own.

Lift a chestnut:
Humans have attributes of name and age, as well as features of eating, sleeping, and introducing themselves.
However, there are different kinds of human beings, no matter what kind of human beings, all have these common characteristics, so we can extract these common features of work, put them in a parent class (that is, superclass or base class), and then inherit the human parent class by the people of all kinds, thus achieving the inherited characteristics.

Prople class

public class People {

    private String name;
    private int age;

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

    public void eat(){
        System.out.println(name + "I am eating!");
    }

    public void sleep(){
        System.out.println(name + "Sleeping!");
    }

    public void sayHello(){
        System.out.println("Hello, I am" + name + ",This year" + age + "Years old!");
    }
}

Chinese class

public class Chinese extends People{

    private String name;

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

    public void color(){
        System.out.println(name + "Yellow!");
    }

    public static void main(String[] args) {
        Chinese chinese = new Chinese("Chinese people",21);
        chinese.eat();
        chinese.sleep();
        chinese.sayHello();
        chinese.color();
    }
}

Run result:
Chinese are eating!
Chinese people are sleeping!
Hello, I am a Chinese, 21 years old!
Chinese are yellow! (Subcategory here) Chinese A trait that extends itself and is not defined in the parent class)

American Class

public class American extends People {

    private String name;

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

    public void color(){
        System.out.println(name + "White!");
    }

    public static void main(String[] args) {
        American american = new American("American",20);
        american.eat();
        american.sleep();
        american.sayHello();
        american.color();
    }
}

Run Results:
Americans are eating!
Americans are sleeping!
Hello, I'm an American. I'm 20 years old!
Americans are Caucasian! (Subclass here) Chinese A trait that extends itself and is not defined in the parent class)

1.4.2, Packaging

Encapsulation is generally thought to bind methods of data and manipulating data, and access to data can only be through defined interfaces. The essence of object-oriented is to portray the real world as a series of fully autonomous, enclosed objects. The way we write in classes is to encapsulate implementation details; we write a class is to encapsulate data and data operations.In other words, encapsulation means hiding everything that can be hidden and providing only the simplest programming interface to the outside world. This mechanism ensures that programs and data are free from external interference and are not misused. The purpose of encapsulation is to protect information. Encapsulation has the following advantages:

  • Good packaging reduces coupling.
  • The structure inside the class can be modified freely.
  • You can control member variables more accurately.
  • Hide information to achieve details.
  • In the object-oriented programming method, Encapsulation refers to a method of encapsulating and hiding the implementation details of abstract function interfaces.
  • Encapsulation can be thought of as a protective barrier against random access of the class's code and data to code defined by an external class.
  • Access to code and data for this class must be controlled through a strict interface.
  • The main function of encapsulation is that we can modify our implementation code without modifying the program snippets that call our code
  • Proper encapsulation can make program code easier to understand and maintain, and also enhance the security of program code.


Create a new Animal class:
(1) Modify the visibility of attributes to restrict access to attributes (generally restricted to private),

public class Animal {
    private String name;
    private int age;
}

In this code, the name and age attributes are set to private, accessible only to this class, and inaccessible to other classes, thus hiding the information.

(2) Provide public method access to each value attribute, that is, create a pair of assignment methods for accessing private attributes

public class Animal {
    
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

(3) Test how these private properties are accessed and set property values

public static void main(String[] args) {

        Animal animal = new Animal();
        animal.setName("Two Dogs");
        animal.setAge(2);
        System.out.println("name: " + animal.getName() + ";age: " + animal.getAge());
}
    
Run result:
name: Two Dogs;age: 2

1.4.3, Polymorphism

Polymorphism refers to the ability to allow objects of different subtypes to respond differently to the same message. Simply put, the same object references the same method but does different things; it can also be understood that the same behavior has multiple different representations or forms.Polymorphisms are also categorized as compile-time polymorphism and run-time polymorphism. If the method of an object is treated as a service provided by the object to the outside world, then run-time polymorphism can be understood as: When system A accesses the service provided by system B, system B has many ways of providing services, but everything is transparent to system A. Method overload What is achieved is compile-time polymorphism (also known as pre-binding), while method override implements runtime polymorphism (also known as post-binding). Runtime polymorphism is the essence of object-oriented.

Advantages of polymorphism:

  • Eliminating coupling between types
  • Replaceability
  • Scalability
  • Interface
  • flexibility
  • Simplify lines

There are three essential conditions for polymorphism to exist:

  • inherit
  • Rewrite
  • Parent reference points to child class object: Parent p = new Child();

    The above examples clearly show two characteristics of polymorphism, method override and parent object pointing to subclass references, that is, the same printer (parent) points to two different printer instances (subclasses), and the same event acts on different subclass instances to produce different results.

Virtual function:
Virtual function exists for polymorphism. There is no concept of virtual function in Java. Its normal function is equivalent to virtual function in C++. Dynamic binding is the default behavior of Java. If you do not want a function to have virtual function feature in Java, you can add final keyword to make it non-virtual.

Lift a chestnut:
Employee class

public class Employee {

    private String name;
    private String address;

    public Employee(String name, String address) {
        System.out.println("Employee Constructor");
        this.name = name;
        this.address = address;
    }
    public void mailCheck() {
        System.out.println("Mail check to: " + this.name
                + " " + this.address);
    }

    public String getName() {
        return name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String newAddress) {
        address = newAddress;
    }
}

Salary class

public class Salary extends Employee {

    private double salary;

    public Salary(String name, String address,double salary) {
        super(name, address);
        this.salary = salary;   //Or setSalary(salary);
    }

    public double getSalary() {
        return salary;
    }
    public void setSalary(double newSalary) {
        if(newSalary >= 0.0) {
            salary = newSalary;
        }
    }
    public double computePay() {
        System.out.println("Calculate wages paid to:" + getName());
        return salary/52;
    }

    public void mailCheck() {
        System.out.println("Salary Class mailCheck Method ");
        System.out.println("Mail check to:" + getName() + " ,Wages are:" + salary);
    }
}

test

public static void main(String[] args) {
        Salary s = new Salary("staff A", "Beijing", 3600.00);
        s.mailCheck();

        System.out.println("------------------------------------");

        Employee e = new Salary("staff B", "Shanghai", 2400.00);
        e.mailCheck();


}

Run result:
Employee Constructor
Salary Class mailCheck Method 
Mail check to: Employee A ,Wage: 3600.0
------------------------------------
Employee Constructor
Salary Class mailCheck Method 
Mail check to: Employee B ,Wage: 2400.0

(4) Abstraction: Abstraction is the process of summarizing the common characteristics of a class of objects to construct a class, including data abstraction and behavior abstraction. Abstraction only focuses on what attributes and behaviors the object has, not on what the details of these behaviors are.

Note: By default, Object Oriented has three main features, encapsulation, inheritance and polymorphism. If the interviewer asks for four of the four Object Oriented features, then the abstract feature can be added.

1.5. Differences between access modifiers

ModifierCurrent ClassSame PackageSubclassOther packages (classes)
public
protectedX
Default (not written by default)XX
privateXXX

Tags: Java Polymorphism encapsulation inheritance

Posted on Sat, 18 Sep 2021 11:52:08 -0400 by Refused