Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Abstract programming
We refer to the elements in the problem space and their representations in the solution space as “objects.” Of course, there are other objects that have no counterparts in the problem space. By adding new object types, the program can be flexibly adapted to suit a particular problem. Programming objects also have something in common with real-world “objects” or “objects” : they have their own states and behaviors. For example, dog states include names, colors, etc., and dog behaviors include barking, tail wagging, etc.
Objects in the software world are similar to objects in the real world. Objects store their state in fields and expose their behavior through methods. Method operates on the internal state of objects and serves as the primary mechanism for communication between objects. Hiding the internal state of objects and performing all interactions through methods is a fundamental principle of object-oriented programming, data Encapsulation.
Everything is an object. Think of an object as a new kind of variable; It holds data, but can be asked to operate on itself. In theory, all the conceptual components of the problem to be solved can be derived and then expressed as an object in the program.
A program is a collection of objects; Through messaging, each object knows what to do. To make a request to an object, “send a message” to that object. More specifically, you can think of a message as an invocation request that invokes a subroutine or function that is subordinate to the target object.
Each object has its own storage space for other objects. Or, by encapsulating existing objects, new types of objects can be made. So, although the concept of an object is very simple, it can be arbitrarily complex in a program.
Every object has a type. According to the syntax, each object is an instance of a class. Class is a synonym for Type. The most important characteristic of a class is “What messages can BE sent to it?” .
All objects of the same class can receive the same message. Since an object of type “Circle” is also an object of type “Shape,” a Circle is fully capable of receiving Shape messages. This means that the program code can command the shape and automatically control all objects that fit the description of the shape, which naturally includes the circle. This feature is called “replaceability” of objects and is one of the most important concepts of OOP.
Class (Class)
In the real world, you will often find many individual objects of the same kind. There could be thousands of other bikes, all of the same make and model. Each bike is built from the same set of design drawings and therefore contains the same components. In object-oriented terms, we say that your bike is called an instance of a class of Objects. A class is a design drawing that creates a single object.
Here is an implementation of the Bicycle class:
class 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(a) {
System.out.println("cadence:" +
cadence + " speed:" +
speed + " gear:"+ gear); }}Copy the code
The fields cadence, Speed, and gear are the state of the object, and the methods changeCadence, changeGear, and speedUp define interactions with the outside world.
You may have noticed that the Bicycle class does not contain a main method. This is because it is not a complete application. This is a design drawing of the bike that might be used in the app. Creating and using the new Bicycle object is the responsibility of the other classes in the application.
Here is the BicycleDemo class, which creates two separate Bicycle objects and calls their methods:
class BicycleDemo {
/ * * *@param args
*/
public static void main(String[] args) {
// Create two different
// Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
// Invoke methods on
// those objects
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(); }}Copy the code
Execute the program with the output:
cadence:50 speed:10 gear:2
cadence:40 speed:20 gear:3
Copy the code
Interface
All objects, though unique, are part of a set of objects that have common characteristics and behaviors.
Each object can only accept specific requests. The requests we make to an object are defined by its “Interface,” and the object’s “type,” or “class,” defines its Interface form. The equivalence or correspondence between “type” and “interface” is the basis of object-oriented programming.
Light lt = new Light();
lt.on();
Copy the code
In this example, the name of the type/class is Light and the name of the Light object is LT, and the requests you can make to the Light object include turning on, turning off, getting Brighter or dim.
By simply defining a “reference” (LT), we create a Light object and use the new keyword to request the object created by that class. To send a message to the object, we list the object name (lt) with a period symbol (.) Concatenate it with message name (ON). As you can see, the code we use in our programs is very simple and intuitive when using some predefined classes.
The following interfaces can be defined for the behavior of a bicycle:
interface Bicycle {
// wheel revolutions per minute
void changeCadence(int newValue);
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
Copy the code
ACMEBicycle implements this interface, using the implements keyword:
class ACMEBicycle implements Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
@Override
public void changeCadence(int newValue) {
// TODO Auto-generated method stub
}
@Override
public void changeGear(int newValue) {
// TODO Auto-generated method stub
}
@Override
public void speedUp(int increment) {
// TODO Auto-generated method stub
}
@Override
public void applyBrakes(int decrement) {
// TODO Auto-generated method stub
}
Copy the code
Note: the public keyword must be added before the implementation method of the interface.
Package (Package)
A package is a namespace that organizes related classes and interfaces. Conceptually, it is similar to a folder on a computer, used to sort various files.
The Java platform provides a huge library of classes (collections of packages) called application program interfaces, or apis for short. Its packages represent the most common general-programming related tasks.
For example, a String object contains the state and behavior of the String; File objects allow programmers to easily create, delete, examine, compare, or modify files in a File system. The Socket object allows the creation and use of network sockets; Various GUI objects create graphical user interfaces. Literally thousands of courses to choose from. As a developer, you only need to focus on the design of a specific application, rather than starting with infrastructure.
Object providing service
When designing a program, you need to think of an object as a provider of services. Objects provide services to users to solve different problems.
For example, in designing a library program, you might imagine that some objects contain predefined inputs, others might be used for book statistics, one for print validation, and so on. This involves breaking a problem down into a set of objects.
Thinking about objects as service providers has an added benefit: it helps improve object cohesion. High cohesion was the basic quality of software design: this meant that aspects of a software component (such as objects, although this could also apply to a method or a library of objects) “cohesion together”. A common problem when designing objects is to combine too much functionality into one object. For example, in your check print module, you can decide that you need to know all about the format and print the object. You may find that this is too much for one object, and you need three or more objects. An object that queries a catalog of information about how to print a check. An object or group of objects can be a generic printing interface that knows all the different types of printers. The third object can use the services of the other two objects to complete the task. Thus, each object has a cohesive set of services it provides. Good object-oriented design, doing one thing for each object, but not trying to do too much.
Using objects as service providers is a great simplification tool. This is useful not only during the design process, but also when others are trying to understand your code or reuse objects. If you can see that an object gets its value based on what services it provides, it can more easily adapt it to your design.
encapsulation
Encapsulation is one of the characteristics of object orientation and is the main feature of object and class concepts.
Encapsulation is to encapsulate objective things into abstract classes, and classes can only allow their data and methods to be operated by trusted classes or objects, to hide the information of the untrusted.
Advantages of encapsulation
- Isolate change
- Easy to use
- Improve reuse
- Improved security
Disadvantages of encapsulation:
The variable and so on use private modification, or encapsulation into the method, so that it can not be directly accessed, increased access steps and difficulty!
The implementation form of encapsulation
- A. Use access modifier private When defining A JavaBean, use private to modify member variables. At the same time, use set and GET methods to access members that are not directly accessible in other classes.
- B. Defining a Java class and Java methods is one of the simplest and most common object-oriented encapsulation operations. These operations follow the idea of hiding implementation details and providing access.
inheritance
One of the main features of object-oriented programming (OOP) languages is inheritance. Inheritance is the ability to take all the functionality of an existing class and extend it without having to rewrite the original class.
New classes created by inheritance are called subclasses or derived classes.
The inherited classes are called “base classes,” “superclasses,” or “superclasses.”
The process of inheritance is the process of going from general to particular.
Inheritance can be achieved by means of Inheritance and Composition.
In the Java language, a class can only be single-inherited and can implement multiple interfaces. Inheritance is when a subclass inherits the characteristics and behavior of its parent class, making its objects have the non-private properties and methods of the parent class.
Class inheritance format
The extends keyword declares that a class extends from another class, as in:
-
The class parent class {}
-
Class extends extends parent {}
Why inheritance?
- Reduce code duplication and bloat and improve code maintainability.
Inherited features
- Subclasses have non-private properties and methods of their parent class;
- Subclasses can have their own attributes and methods (extending the parent class);
- Java is single-inheritance (each subclass can inherit only one parent class); But Java can be multiple inheritance (e.g., A inherits B, B inherits C).
Super and this keywords:
-
Super keyword: We can use the Super keyword to enable subclasses to access members of the parent class, referring to the parent class of the current instance object.
-
This keyword: a reference to the instance object itself.
polymorphism
Object – oriented three characteristics: encapsulation, inheritance, polymorphism. From a certain point of view, encapsulation and inheritance are almost always ready for polymorphism.
Definition of polymorphism: Allows objects of different classes to respond to the same message. That is, the same message can behave in many different ways depending on the object to which it is sent. (Sending a message is a function call.)
The technique to achieve polymorphism is called Dynamic binding, which refers to the determination of the actual type of the referenced object during execution and the call of its corresponding method according to its actual type.
What polymorphism can do: Decouple types.
In reality, there are numerous examples of polymorphism. For example, if you press F1, the Word help will pop up under Word. What pops up under Windows is Windows Help and Support. The same event occurring on different objects produces different results.
There are three necessary conditions for the existence of polymorphism:
- There should be inherited
- Want to have to rewrite
- A superclass reference points to a subclass object.
Benefits of polymorphism:
- Substitutability. Polymorphism is replaceable for existing code. For example, polymorphisms work for the Circle class, as well as for any other circular geometry, such as a Circle.
- Extensibility. Polymorphism is extensible to code. Adding new subclasses does not affect the operation and operation of polymorphism, inheritance, and other features of existing classes. It’s actually easier to add a new subclass to get polymorphic functionality. For example, it is easy to add polymorphism of sphere class to the polymorphism of cone, semi-cone, and semi-sphere.
- Interface-ability. Polymorphism is implemented when a superclass provides a common interface to subclasses through method signatures that subclasses can complete or override. The Shape superclass in the figure specifies two interface methods for implementing polymorphism, computeArea() and computeVolume(). Subclasses, such as Circle and Sphere, complete or override these two interface methods to implement polymorphism.
- Flexibility. It embodies flexible and diversified operation in application and improves the use efficiency.
- Simplicity. Polymorphism simplifies the code writing and modification process of application software, especially when dealing with a large number of object operations and operations, this feature is particularly prominent and important.