编程知识 cdmana.com

Overview of Java object oriented


Part of this paper is excerpted from On Java 8


object-oriented programming

When it comes to object orientation , I have to mention another concept : abstract . The ultimate goal of programming is to solve a problem , The complexity of the problem depends directly on the type and quality of the abstraction . Early assembly languages used to abstract the underlying machine slightly , To the later C Language is the abstraction of assembly language . For all that , Their abstract principles still require us to focus on the underlying structure of the computer , Not the problem itself

object-oriented programming (Object-Oriented Programming OOP) It's a programming mindset and coding architecture . Different from the traditional process oriented programming , Object oriented programming takes problem space ( Actual problems to be solved ) The elements in and their representation in solution space are expressed in a universal way , This representation is called an object (Object). For objects that cannot be mapped in the problem space , We can also add new object types , In order to solve specific problems . To make a long story short ,OOP Allow us to describe the problem in terms of the problem , Not based on the solution to the problem . Each object has its own state , And you can do specific operations , In other words , They all have their own characteristics and behaviors

According to the concept of object-oriented programming , Five basic characteristics can be summed up :

  • Everything is object
  • A program is a set of objects , You can send messages to each other to tell each other what to do
  • Each object has its own storage space , To accommodate other objects
  • Each object has a type
  • All objects of the same class can receive the same message

A more concise description of an object is : An object has its own state 、 Behavior and identity , This means that objects have their own internal data ( state )、 Method ( Behavior ), And distinguish them from each other ( Each object has a unique address in memory )


Interface

All objects are unique , But it's also part of the class to which objects with the same characteristics and behaviors belong . This idea is applied to object-oriented programming , And use the basic keywords in the program class To represent type , Each class has its own common characteristics and behaviors . After creating a class , Many objects can be generated , These objects are treated as elements in the problem to be solved . in fact , When we're doing object-oriented programming , One of the biggest challenges is : How to establish an ideal one-to-one mapping relationship between the elements of problem space and solution space ?

If you can't build a valid mapping , Objects can't really do useful work , There has to be a way to make a request to an object , Make it solve some practical problems , Like finishing a deal 、 Turn on a switch, etc . Only each specific object can receive , The requests we make to an object are defined through its interface

For example, there is a kind of electric light Light, We can approach Light Object requests include opening on、 close off, So in Light Class we need to define two methods on() and off(), And then create a Light Object of type , And call its interface method

OK. You've found out , The object receives the request and feeds back the result , So we can think of an object as a provider of a service , That is to say, it will provide services for your users , And it can do this by invoking services provided by other objects . Our ultimate goal is to develop or call some existing objects in the tool library , Providing the ideal service to solve problems

Further more , We need to break it down , Abstract it into a set of services , And organized division of each single function 、 Modules that work well and closely , Avoid cramming too many functions into one object . Such programming can improve the reusability of code , At the same time, it is convenient for others to read and understand our code


encapsulation

We divide the focus area of programming into R & D and application . The application programmer calls the basic tool class built by the R & D programmer to do rapid development , R & D programmers develop a tool class , The utility class only exposes the necessary content to the application programmer , And hide the details of the internal implementation , This can effectively prevent the tool class from being misused and changed . obviously , We need some methods to ensure the correct use of tool classes , Only set access control , Only in this way can we solve this problem fundamentally

therefore , There are two reasons for using access control :

  1. Let application programmers not touch parts they shouldn't touch
  2. The creator of the class library can improve and update the tool library without affecting the use of others

Java Three explicit keywords are provided to set access to the class , Namely public( Open )、private( private ) and protected( The protected ), These access modifiers determine who can use the methods they decorate 、 Variable or class

  1. public

    Indicates that anyone can access and use the element

  2. private

    In addition to the inner class and methods , The element cannot be accessed directly by the outside world

  3. protected

    By protected The decorated members are visible to this package and its subclasses . This sentence is a little too general , More specifically, it should be :

    • The base class protected It's visible in the bag
    • If the subclass is not in the same package as the base class , Then the subclass instance can access the inherited from the base class protected Method , And can't access the base class instance protected Method
  4. default

    If you don't use the first three , The default is default jurisdiction , Resources under this permission can be accessed by members of other classes in the same package


Reuse

Reusability of code and design is one of the advantages of object-oriented , We can achieve reusability by reusing objects of a class , for example , Use the object of one class as a member variable of another class . therefore , The newly formed class can be made up of any number and type of other objects , Here are two concepts of composition and aggregation :

  • Combine (Composition) Often used to indicate ownership (has-a relationship) for example , Car has engine . In a combinatorial relationship , The whole piece has the life cycle of the part , So when the whole piece is deleted , The part will be deleted with it
  • polymerization (Aggregation) Represents a dynamic combination . In an aggregate relationship , The whole piece will not have the life cycle of the part , So when the whole piece is deleted , Parts will not be deleted

Using composition can bring great flexibility to our program . Usually in a newly created class , Member objects use private Access right , In this way, application programmers can't access it directly , We can do this without affecting the customer code , Take the time to modify those members . We can also change member objects at run time , In order to dynamically change the behavior of the program . The inheritance mentioned below does not have this flexibility , Because the compiler limits classes created by inheritance


Inherit

The concept of object brings convenience to programming , It allows us to encapsulate all kinds of data and functions together , In this way, the concept of problem space can be properly expressed , Instead of having to use the underlying machine language

adopt class keyword , Can form the basic unit of programming language . Unfortunately , There are still many problems in doing so : After creating a class , Even if another new class has a similar function , You still have to recreate a new class . If we can take advantage of existing data types , Clone it , Then add and modify according to the situation , That would be a lot more convenient . Inheritance is designed for that , But inheritance is not the same as cloning . In the course of inheritance , Such as primitive class ( Base class 、 Parent class ) There is a change , Cloned modified classes ( Subclass 、 Derived class ) It also reflects this change

There are usually multiple derived classes , And contains all the features and behaviors shared between the types derived from it . The latter may contain more features than the former , And can handle more messages ( Or deal with them in a different way )

Using inheritance , You're going to build a type hierarchy , To represent a type of problem you are trying to solve . A common example is shape , Every shape has a size 、 Color 、 Location, etc , Each shape can be drawn 、 erase 、 Mobile, etc , You can also derive specific types of shapes , Like a circle 、 Square 、 Triangles and so on . Each shape derived can have additional features and behaviors , for example , Some shapes can be flipped , The formulas for calculating the shape area are different from each other and so on

The type hierarchy reflects the similarity and difference between shapes , You don't need to build many intermediate models between the problem description and the solution description . Inherit from an existing type and create a new type , The new type contains not only all the members of the existing type ( Although private members are hidden and inaccessible ), More importantly, it replicates the interface of the base class . in other words , The base class object can receive messages, and the derived class object can also receive . If the base class doesn't meet your needs , You can add more methods to derived classes , Even change the behavior of existing base class methods ( Cover ), Just redefine the method in the derived class


polymorphic

When dealing with class hierarchies , Usually, an object is regarded as the base class it belongs to , Instead of treating it as a concrete class , In this way , We can write code that's not limited to specific types of code . For example, an example of the shape above , Methods manipulate generic shapes , It doesn't care whether it's a circle or a triangle . All shapes can be drawn 、 Erase and move . So the method sends a message to any of the objects that represent the shape without worrying about how the object handles the information

This ability improves our design , Reduce the cost of software maintenance . If we unify the derived object type as its base class , The compiler can't know exactly which shape is drawn when compiling , That kind of car is moving , That's the point : When the program receives this message , Programmers don't care which code will be executed , The drawing method can be applied equally to every possible shape , Shapes execute the appropriate code based on their specific types

therefore , We can add a new subclass with different execution modes without changing the method that calls it , More conducive to program expansion . So how does the compiler determine which part of the code to execute ? Generally speaking , The compiler cannot make function calls , For non OOP Function calls generated by the compiler can cause so-called early binding , This means that the compiler generates a call to a specific function name , The call is resolved to the absolute address of the code to be executed . Object oriented languages use the concept of late binding , When sending information to an object , The called code is not determined until run time , All the compiler has to do is make sure that the method exists , And perform type checking on parameters and return values , But I don't know the exact code to execute

To perform late binding ,Java Use a special code bit instead of an absolute call , This code uses the information stored in the object to calculate the address of the method body . therefore , The behavior of each object varies according to the content of a particular code bit . When you send a message to an object , Object knows how to handle this message . In some languages such as C++ Methods must be explicitly granted the flexibility to bind properties later , And in the Java in , Dynamic binding is the default behavior , No extra keywords are required to implement polymorphism

When sending a message to an object , If the program doesn't know what the specific type of reception is , But in the end, the execution is right , This is the polymorphism of objects . Object oriented programming language realizes the polymorphism of objects by dynamic binding , The compiler and the runtime system are responsible for controlling all the details . We just need to know what to do , And how to use polymorphism to better design programs


Object creation and lifecycle

One of the key issues to pay attention to when using objects is how to create and destroy objects . Every object needs resources to survive , Especially memory . When the object is no longer in use , We should release resources in time , Clean up memory

However , The actual situation is often much more complicated . How do we know when to clean up these objects ? Maybe an object is processed in a system , But in other systems, it may not be finished yet . in addition , Where is the object's data ? How to control its life cycle ? stay C++ The idea adopted in the design is efficiency first , It gives the programmer the choice of these issues . When programmers write programs , By placing objects on a stack or static storage area to determine the memory footprint and living space . Relative , We also sacrifice the flexibility of the program

Java Using dynamic memory allocation , Dynamically create objects in heap memory . In this way , We don't know how many objects are created until the program runs 、 Type of survival and time . It may take longer to create space on heap memory than stack memory ( But not necessarily ), But the dynamic distribution theory holds that : Objects are usually complex , Compared to the overall cost of object creation , The cost of finding and freeing memory space is negligible . For the life cycle of objects , stay C++ You have to programmatically determine when to destroy an object , and Java The garbage collection mechanism can automatically find objects that are no longer used and free corresponding memory space , bring Java The coding process of is compared with C++ It's a lot easier


版权声明
本文为[Murmur without speaking]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224170726023B.html

Scroll to Top