Object-oriented programming concepts

Question: What is an object ? What is a class ? What is inheritance ? What is an interface ? What is a bag ?

Understand the concept of Object

Object is the key to understanding object-oriented technology. Now look around and you will find many examples of real objects: your dog, desk, TV, bicycle.

Objects in the real world share two characteristics :
they all have state and behavior. For example, a dog has a State (name, color, breed, hunger) and Behavior (barking, catching, wagging tail). Bicycles also have status (current gear, current pedal rhythm, current speed) and behavior (shift gears, change pedal rhythm, apply brakes). Recognizing the state and behavior of real-world objects is a good way to think from the perspective of object-oriented programming.

Take a minute to observe real objects in the area near you. For each object you see, ask yourself two questions:
"What state might this object be in?" and "What behavior might this object perform?".
Make sure to write down your observations. As you perform operations, you will notice that the complexity of objects in the real world varies.
Your desktop light may only have two possible states (on and off) and two possible behaviors (on, off), but the desktop radio may have other states (on, off, current volume, current station) and Behavior (open), close, increase volume, decrease volume, search, scan and adjust).
You may also notice that some objects will also contain other objects. These real observations are transformed into the world of object-oriented programming.

Methods: Methods: Fields:
Insert picture description here
Software objects are conceptually similar to objects in the real world: they are also composed of states and related behaviors. Objects store their state in fields (variables in some programming languages) and expose their behavior through methods (functions in some programming languages). Methods operate on the internal state of objects and are used as the main mechanism for communication between objects. Hiding the internal state and requiring all interactions to be performed through an object method is called data encapsulation-the basic principle of object-oriented programming.

Consider a bicycle, for example:
Change gears:
Brake: Brake
Change cadence: Change the cadence:
Insert picture description in Change
By attributed to the state (current speed, current pedal cadence and current gear) and provide a way to change the state, the object can control the outside world How to use it. For example, if the bicycle has only 6 gears, the method of changing gears may reject any value less than 1 or greater than 6.

Bundling code into a single software object brings many benefits, including:

Modularization:
The source code of an object can be written and maintained independently of the source code of other objects. After creating the object, you can easily pass the object inside the system.

Information hiding:
By only interacting with the object, the details of its internal implementation are still hidden from the outside world.

Code reuse : If an object already exists (perhaps written by another software developer), it can be used in the program. This allows experts to implement/test/debug task-specific complex objects, and then you can trust them to run in your own code.

Pluggability and ease of debugging : If you find a problem with a particular object, you only need to delete it from the application and insert another object as a replacement. This is similar to solving mechanical problems in the real world. If the bolt breaks, replace it instead of the entire machine.


Understand the concept of class

In the real world, you will often find many individuals of the same kind. There may be thousands of other bicycles, all of the same brand and model. Each bicycle is manufactured according to the same design drawings and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of a class of objects called bicycles. One is the blueprint from which a single object is created.

The following Bicycle class is a possible implementation of bicycle:

class Bicycle{

//
Cadence = 0​​; int cadence = 0;
//speed = 0;
int speed = 0;
//gear=1;
int gear = 1;

void changeCadence(int newValue) {
cadence = newValue;
}

void changeGear(int newValue) {
     gear = newValue;
}

void speedUp(int increment) {
     speed = speed + increment;   
}

void applyBrakes(int decrement) {
     speed = speed - decrement;
}

void printStates() {
     System.out.println("cadence:" +
         cadence + " speed:" + 
         speed + " gear:" + gear);
}

}

The syntax of the Java programming language may seem new to you, but the design of this class is based on the previous discussion of bicycle objects. The fields cadence, speed and gear represent the state of the object, and these methods (changeCadence, changeGear, speedUp, etc.) define its interaction with the outside world.

You may have noticed that the Bicycle class does not contain a main method. That is because it is not a complete application. It is just a blueprint for the bikes that may be used in the app. The responsibility for creating and using a new Bicycle object belongs to some other classes in the application.

This is a BicycleDemo class that creates two separate Bicycle objects and calls their methods:
class BicycleDemo { public void main(String [] args){

    //创建两个不同的 
    //自行车物体
    自行车bike1 =新的Bicycle();
    自行车bike2 =新的Bicycle();

    //在以下位置调用方法 
    //这些对象
    bike1.changeCadence(50);
    bike1.speedUp(10);
    bike1.changeGear(2);
    bike1.printStates();

    bike2.changeCadence(50);
    bike2.speedUp(10);
    bike2.changeGear(2);
    bike2.changeCadence(40);
    bike2.speedUp(10);
    bike2.changeGear(3);
    bike2.printStates();
}

}
The output of this test shows the ending pedal cadence, speed and gear of the two bicycles:

Tempo: 50 Speed: 10 Gear: 2
Tempo: 40 Speed: 20 Gear: 3


**

What is inheritance?

Different kinds of objects usually have a certain amount in common with each other. For example, mountain bikes, road bikes and tandem bicycles all have the characteristics of a bicycle (current speed, current pedal rhythm, current gear). However, each bike also defines other features that make it unique: tandem bikes have two seats and two handlebars; road bikes have lowered handlebars; some mountain bikes have additional chain links, which lowers Gear ratio.

Object-oriented programming allows classes to inherit common state and behavior from other classes. In this example, Bicycle has now become the parent MountainBike, RoadBike and TandemBike. In the Java programming language, every class can have a direct super class, and every super class has an unlimited number of possible subclasses:

Insert picture description here
The hierarchy of bicycle courses.

The syntax for creating subclasses is simple. At the beginning of the class declaration, use the extends keyword, followed by the name of the
class to inherit from: class MountainBike extends Bicycle {

// //定义
//山地自行车的新字段和方法

}
This provides MountainBike with all the same fields and methods as Bicycle, but allows its code to focus only on the features that make it unique. This makes the code of the subclass easier to read. However, you must take care to properly record the state and behavior of each superclass definition, because the code will not appear in the source file of each subclass.


What is an interface (Interface)?

As you know, objects define their interaction with the outside world through their public methods. The method forms the interface between the object and the outside world; for example, the button on the front of the TV is the interface between you and the wire on the other side of the plastic case. You can turn the TV on and off by pressing the "Power" button.

In the most common form, an interface is a set of related methods with an empty body. If you specify the behavior of the bicycle as an interface, it might look like this:

interface Bicycle {

// Wheel revolutions per minute
void changeCadence(int newValue);

void changeGear(int newValue);

void speedUp(int increment);

void applyBrakes(int decrement);

}
To implement this interface, the name of your class will be changed (for example, to a specific brand of bicycle, such as ACMEBicycle), and then implements use keywords in the class declaration:

ACMEBicycle implements Bicycle {

int cadence = 0;
int speed = 0;
int gear = 1;

void changeCadence(int newValue) {
     cadence = newValue;
}

void changeGear(int newValue) {
     gear = newValue;
}

void speedUp(int increment) {
     speed = speed + increment;   
}

void applyBrakes(int decrement) {
     speed = speed - decrement;
}

void printStates() {
     System.out.println("cadence:" +
         cadence + " speed:" + 
         speed + " gear:" + gear);
}

}
Implementing an interface can make the behavior that the class promises to provide more formal. The interface forms a contract between the class and the outside world, and the contract is enforced by the compiler at compile time. If your class claims to implement an interface, all methods defined by the interface must appear in its source code before the class is successfully compiled.


What is a package?

A package is a namespace used to organize a set of related classes and interfaces. Conceptually, you can think of software packages as similar to different folders on your computer. You can keep HTML pages in one folder, images in another folder, and scripts or applications in another folder. Because software written in the Java programming language can be composed of hundreds of individual classes, it makes sense to keep things organized by putting related classes and interfaces into packages.

The Java platform provides a huge class library (a set of software packages) suitable for use in your own applications. This library is called "Application Programming Interface" or "API" for short. Its packages represent the tasks most commonly associated with general programming. For example, a String object contains the state and behavior of the string. A File object allows programmers to easily create, delete, check, compare, or modify files in the file system; a Socket object allows the creation and use of network sockets; various GUI objects control buttons and check boxes, as well as Any other content related to the graphical user interface. Literally, there are thousands of courses to choose from. Programmer, this allows you to focus on the design of a particular application rather than the infrastructure required to make it work.

The Java platform API specification contains a complete list of all packages, interfaces, classes, fields and methods provided by the Java SE platform. Load the page in the browser and add it as a bookmark. As a programmer, it will become your most important reference document.

Guess you like

Origin blog.csdn.net/chaihaiqiang/article/details/112766842