Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Three object-oriented characteristics of Java

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on the "three major object-oriented features of Java", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn the "three object-oriented features of Java".

Three object-oriented characteristics of Java

Object-oriented is referred to as OO (Object Oriented). After 1980s, there has been the research of new system development methods, such as object-oriented analysis (OOA), object-oriented design (OOD), object-oriented programming (OOP) and so on.

To language, everything is an object. Objects in the real world are abstractly embodied in the programming world, and an object represents a specific operation. Each object finally forms a complete program design, which can exist independently or inherit from other objects. The information is transmitted between objects through interaction to realize program development.

The concept of object

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, and the object corresponds to the entity one by one, that is to say, every entity in the real world is an object, it is a kind of concrete concept. The object has the following characteristics:

Objects have properties and behaviors.

The object has a changing state.

The object is unique.

Objects are instances of a category.

Everything is an object, and everything in the real world can be regarded as an object.

The difference between object-oriented and process-oriented

Process oriented:

An early programming idea of   , as its name implies, is that it thinks about problems from a process point of view, emphasizing functional behavior, the execution process of functions, that is, sequence, and each function we use functions (similar to methods) to implement these steps step by step. When you use it, you can call the functions in turn.

Process-oriented design:

The smallest program unit of    is the function, each function is responsible for completing a certain function, which is used to accept the input data, the function processes the input data, and then outputs the result data. the whole software system is composed of functions one by one, in which the function as the entrance of the program is called the main function, and the main function calls other functions in turn, and the ordinary functions can call each other, thus realizing the function of the whole system.

The biggest problem of    process-oriented is that with the expansion of the system, process-oriented will not be able to cope with, and eventually lead to the collapse of the system. In order to solve this kind of software crisis, we put forward the idea of object-oriented.

Process-oriented defects:

   adopts a specified design pattern. In the design stage, we need to consider which sub-modules each module should be divided into, and each sub-module is subdivided into smaller sub-modules, and so on, until the module is subdivided into functions.

Existing problems

The design is not intuitive enough and is inconsistent with human habits of thinking.

The system software has the advantages of poor adaptability, poor expandability and low maintainability.

Object-oriented:

A new process-oriented programming idea, as the name implies, is that the idea is to think from the point of view of objects. We put multiple functions into different objects reasonably, emphasizing the objects with certain functions.

An entity that    has a certain function is called an object. The smallest object-oriented program unit is: class. Object-oriented is more in line with the conventional way of thinking, good stability, strong reusability, easy to develop large-scale software products, and good maintainability.

   in software engineering, object-oriented can make engineering more modular, achieve lower coupling and higher cohesion.

A brief introduction to the three Core Features of object-oriented

Object-oriented development mode is more helpful for people to open up their thinking, facilitate the division of programs in the specific development process, facilitate programmers to divide work and cooperation, and improve development efficiency.

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

1. The concept of inheritance

Inheritance is a cornerstone of java object-oriented programming technology because it allows the creation of hierarchical classes.

Inheritance is that the subclass inherits the characteristics and behavior of the parent class, so that the subclass object (instance) has the instance domain and method of the parent class, or the subclass inherits the method from the parent class, so that the subclass has the same behavior of the parent class.

Rabbits and sheep belong to herbivores, lions and leopards belong to carnivores.

Herbivores and carnivores belong to animals.

So the relationship that inheritance needs to conform to is: is-a, the parent class is more general, and the child class is more specific.

Although herbivores and carnivores are both animals, their properties and behaviors are different, so the subclasses will have the general characteristics of the parent class and will also have their own characteristics.

2. Java polymorphism

Polymorphism is the ability of the same behavior to have many different forms or forms of expression.

Polymorphism is the same interface that uses different instances to perform different operations, as shown in the figure:

Polymorphism is the embodiment of many forms of expression of the object.

In reality, for example, we press the F1 key:

If what currently pops up under the Flash interface is the help document for AS 3

If the current pop-up under Word is Word help

What pops up under Windows is Windows help and support.

The same event occurs on different objects and produces different results.

3. Java encapsulation

In object-oriented programming methods, encapsulation (English: Encapsulation) refers to a method that wraps and hides the implementation details of an abstract function interface.

Encapsulation can be thought of as a protective barrier to prevent code and data of this class from being randomly accessed by code defined by external classes.

Access to the code and data of this class must be controlled through a strict interface.

The main function of encapsulation is that we can modify our own implementation code without having to modify the program fragments that call our code.

Proper encapsulation makes the code easier to understand and maintain, and enhances the security of the code.

Detailed explanation of the three characteristics of object-oriented programming

Object-oriented programming is an idea of using class and object programming. All things can be classified, class is a high degree of abstraction of things in the world, there are different relationships between different things, the encapsulation relationship between a class itself and the outside world, the inheritance relationship between a parent class and a child class, and the polymorphic relationship between a class and multiple classes. All things are objects, objects are concrete things in the world, object-oriented features encapsulation, inheritance, polymorphism, encapsulation, encapsulation explains the relationship between a class's behavior and attributes and other classes, low coupling, high cohesion; inheritance is the relationship between parent and subclasses, polymorphism refers to the relationship between classes and classes.

1. The concept of inheritance

Just as the children in life inherit all the property owned by their parents, the inheritance in the program refers to the method and mechanism by which the subclass has the parent data structure, which is a relationship between classes; inheritance can only be single inheritance.

For example, to define a Chinese teacher class and a math teacher class, if you do not use inheritance, then the properties and methods that need to be defined in the two classes are shown in figure 1.

Fig. 1 attributes and methods in Chinese teacher class and mathematics teacher class

As can be seen from figure 1, many of the attributes and methods in the Chinese teacher class and the mathematics teacher class are the same, and these same attributes and methods can be extracted and placed in a parent class, which is used to be inherited by the Chinese teacher class and the mathematics teacher class. Of course, the parent class can also inherit other classes, as shown in figure 2.

Figure 2 sample diagram of parent class inheritance

Summarize the inheritance relationship in figure 2, which can be represented by a general tree relationship, as shown in figure 3.

Figure 3 sample diagram of class inheritance

It can be seen from figure 3 that the main personnel of the school are a large category, teachers and students are two subcategories of the main personnel of the school, and teachers can be divided into two subcategories: Chinese teachers and math teachers, and students can also be divided into two subcategories: monitor and group leader.

The purpose of using this hierarchical classification is to extract the common properties and methods of multiple classes and put them in their parent classes, and then only need to define their own unique properties and methods in the subclasses. and get their common properties and methods in the parent class in the form of inheritance.

Inheritance is a class-to-class relationship, a "is a" relationship. For example, "dogs" inherit "animals", where animals are the parent or base class of dogs, and dogs are subclasses or derivatives of animals. As shown in the following figure:

Note: inheritance in java is single inheritance, that is, a class has only one parent class.

Add: inheritance in Java can only be inherited only, but multiple inheritance can be achieved by inheriting other classes from inner classes.

Public class Son extends Father {public void go () {System.out.println ("son go");} public void eat () {System.out.println ("son eat");} public void sleep () {System.out.println ("zzzzzz");} public void cook () {/ / Multi-inheritance new Mother (). Cook () implemented by anonymous inner classes; / / the inner class inherits the second parent class to achieve multi-inheritance Mom mom = new Mom (); mom.cook () } private class Mom extends Mother {@ Overridepublic void cook () {System.out.println ("mom cook");}} 2, benefits of inheritance

The subclass has all the properties and methods of the parent class (except those modified by private), thus realizing the reuse of the code.

3. Grammar rules

A. method rewriting

If a subclass is not satisfied with the method of the inherited parent class, it can write its own inherited method, which is called method rewriting. When a method is called, the method of the subclass is called first.

Note that when rewriting:

A, return value type

B, method name

C, type and number of parameters

It is called a method rewriting only if it is the same as the method inherited by the parent class.

The difference between overloading and rewriting:

Method overloading: a polymorphic means of dealing with multiple identical method names for different data in the same class.

Method rewriting: distinguishing changes are made to methods that already exist in the parent class in the subclass as opposed to inheritance.

B. initialization order of inheritance

1. Initialize the parent class and then initialize the subclass

2. First perform the properties in the initialization object, and then perform the initialization in the constructor.

Based on the above two points, we know that instantiating a subclass, the execution order of the java program is:

Parent object attribute initialization-- > parent object construction method-- > subclass object attribute initialization-- > subclass object construction method

Here is a graphic picture:

C, final keywords

Using the final keyword for identification has a "final" meaning.

1. Final decorates the class, then the class is not allowed to be inherited.

2. Final modification method, the method is not allowed to be overridden (overridden).

3. Final modifies the property, which is not implicitly initialized for the class, so the initialization property of the final property must have a value or be assigned in the constructor (but you can only choose one, and you must choose one, because there is no default value!) And cannot be changed after initialization, it can only be assigned once.

4. Final modifies a variable, then the value of the variable can only be assigned once, and it can only be assigned when the variable is declared, that is, it becomes a constant.

D, super keywords

Used inside the object, it can represent the parent class object.

1. Access the attribute of the parent class: super.age

2. The method to access the parent class: super.eat ()

Application of super:

First of all, we know that the constructor of the parent class must be called during the construction of the subclass. In fact, our super keyword has been implicitly used in this process.

This is because if the constructor that calls the parent class is not shown in the constructor of the subclass, the system calls the constructor with no arguments to the parent class by default.

So if you use the super keyword to call the constructor of the parent class in the subclass, you must be in the first line of the constructor of the subclass.

It is important to note that if the constructor of the subclass does not show the constructor that invokes the parent class, and the parent class does not have a constructor without parameters, the compilation error occurs.

(add that although the no-parameter constructor of the declared parent class is not displayed, the system will automatically generate a no-parameter constructor by default, but if you declare a parameterized constructor instead of declaring a parameterless constructor, the system will not generate a parameter-free constructor by default, which is called whether the parent class has parameters or not. )

Second, the concept of encapsulation.

Encapsulation is a programming mechanism that binds code and the data it processes, which ensures that programs and data are free from external interference and misuse. The purpose of encapsulation is to protect information. The main advantages of using it are as follows.

Protects the information in the class, which prevents externally defined code from accessing internal code and data at will.

Hide the details, some information that does not need to be modified and used by programmers, such as the keyboard in the cash machine, the user only needs to know which key to press to achieve what operation, as for its internal operation, the user does not need to know.

It is helpful to establish the loose coupling relationship between each system and improve the independence of the system. When the implementation of a system changes, as long as its interface remains unchanged, it will not affect the use of other systems. For example, no matter how the storage mode of the U disk is changed, as long as the USB interface on the U disk remains unchanged, it will not affect the normal operation of the user.

Improve the reuse rate of software and reduce the cost. Each system is a relatively independent whole and can be used in different environments. For example, a U disk can be used on multiple computers.

The basic encapsulation unit of the Java language is the class. Because the purpose of a class is to encapsulate complexity, there is a mechanism to hide implementation complexity within the class. Java provides private and public access modes, the public interface of the class represents everything that external users should or can know, and private method data can only be accessed through the member code of the class, which ensures that unwanted things will not happen.

2. Advantages of encapsulation

In object-oriented programming methods, encapsulation (English: Encapsulation) refers to a method that wraps and hides the implementation details of an abstract function interface.

Encapsulation can be thought of as a protective barrier to prevent code and data of this class from being randomly accessed by code defined by external classes.

Access to the code and data of this class must be controlled through a strict interface.

The main function of encapsulation is that we can modify our own implementation code without having to modify the program fragments that call our code.

Proper encapsulation makes the code easier to understand and maintain, and enhances the security of the code.

Advantages of encapsulation

Good packaging can reduce coupling.

The structure within the class can be modified freely.

You can have more precise control over member variables.

Hide information and implement details.

Java encapsulation, to put it bluntly, is to put a large mass of common implementation logic into a box (class), where the entrances and exits are all on the box. If you want to use this box, connect the entrance and exit, you can use it, you can throw it directly without it, and it will have no effect on your code.

For programmers, the purpose of using encapsulation is:

Lazy, hard work, later can knock a lot of code, enhance the reusability of the code

Simplify the code and look easier to understand

Hide the core implementation logic code, simplify the external logic, and don't let others modify it, as jar does

One-to-one, one function only serves this function; avoid using the hair rope together, resulting in the last mess

3. Implementation steps of encapsulation

It is important to note that encapsulated properties do not have to go through the get/set method, and other methods can also operate on encapsulated properties. Of course, it is best to use the get/set method, which is more standard.

A, access modifier

It can be seen from the table that the encapsulation from top to bottom is getting worse and worse.

B, this keyword

The 1.this keyword represents the current object

This. Property manipulates the properties of the current object

This. Method calls the method of the current object.

two。 The this keyword is often used when encapsulating the properties of an object.

3. You can use the this** distinction when the parameter names of the getter and setter functions coincide with the member function names. Such as: * *

Inner classes in C, Java

An inner class (Inner Class) is a class defined in another class. In contrast, a class that contains an inner class is called an outer class.

So the question is: then why define one class in another? How nice it is to have a refreshing independent class!

A: the main functions of inner classes are as follows:

1. The inner class provides a better encapsulation to hide the inner class within the outer class and not allow other classes in the same package to access the class.

two。 The methods of the inner class can directly access all the data of the external class, including private data.

3. The functions implemented by inner classes can also be implemented using external classes, but sometimes it is more convenient to use them.

Inner classes can be divided into the following categories:

Member inner class

Static inner class

Method inner class

Anonymous inner class

Third, polymorphism 1. The concept of polymorphism

Object-oriented polymorphism, that is, "one interface, multiple methods". Polymorphism is reflected in that the properties and methods defined in the parent class can have different properties or expressions after they are inherited by the subclass. Polymorphism allows an interface to be used by more than one kind, which makes up for the deficiency of single inheritance. The concept of polymorphism can be represented by a tree relationship, as shown in figure 4.

Fig. 4 polymorphic example diagram

As can be seen from figure 4, many attributes and methods in the teacher class can be used by both the Chinese teacher class and the math teacher class, which is not easy to make mistakes.

2. The benefits of polymorphism

Substitutability (substitutability). Polymorphism is replaceable for existing code. For example, the polymorphic Circle class works for circles, as well as for any other circular geometry, such as torus.

Scalability (extensibility). Polymorphism is extensible to code. Adding new subclasses does not affect the polymorphism, inheritance, and operation of other features of existing classes. In fact, the new subclass makes it easier to get polymorphic functionality. For example, on the basis of realizing the polymorphism of cones, semi-cones and hemispheres, it is easy to add the polymorphism of spheres.

Interface (interface-ability). Polymorphism is implemented by a superclass that provides a common interface to a subclass through a method signature, which is perfected or overridden by a subclass.

Flexibility (flexibility). It embodies flexible and various operations in the application, and improves the use efficiency.

Simplicity (simplicity). Polymorphism simplifies the process of writing and modifying the code of application software, especially when dealing with a large number of object operations and operations, this feature is particularly prominent and important.

The father class of the offspring is instantiated, and then it is equivalent to a father who has many sons, and the courier sends something to the father's son, he only needs to send it to the father's home, as for the specific son, the father will not be able to distinguish between his own son, so you don't have to worry about it.

Using polymorphism is a good habit

Polymorphic declaration is a good habit. When we create a class that uses only its superclass or interface-defined methods, we can declare its index as its superclass or interface type.

Its advantage is that if one day the way we implement this interface method changes, and there is a new implementation class for this interface, our program also needs to use the latest implementation, as long as the object implementation is modified. The index does not need to change.

Like Map.

< String,String>

Map = new HashMap

< String,String>

()

If you want to switch to HashTable implementation, you can Map.

< String,String>

Map = new HashTable

< String,String>

()

For example, if you write a method that requires the List type to be passed, you can pass it with list in List list = new ArrayList (), but you can't pass it as ArrayList list = new ArrayList (). Although it is handled in the same way. In addition, the method can be handled differently according to the different list (ArrayList or LinkList) you pass.

3. Polymorphism in Java

The polymorphism in java is mainly manifested in two aspects:

A, citation polymorphism

A reference to a parent class can point to an object of this class

A reference to a parent class can point to an object of a subclass

What do these two sentences mean? let's try it with code. First, let's create a parent class Animal and a subclass Dog, as shown in the main function:

Note: we cannot use a reference to a subclass to point to the object of the parent class, such as:.

Here we must deeply understand the meaning of citation polymorphism in order to better remember the characteristics of this polymorphism. Why can't references of subclasses be used to point to objects of the parent class? I would like to explain to you here: taking the above example, we can say that "a dog is an animal", but we cannot say that "an animal is a kind of dog". Dogs and animals are the inheritance relationship between parents and children, and their subordination cannot be reversed. When the reference of the parent class points to the object of the child class, the object will only be regarded as a special parent class (with overridden methods and properties). On the contrary, it is not feasible for a reference of a subclass to point to the object of the parent class!

B. Method polymorphism

The two objects created above, this class object and subclass object, are also references to the parent class, and when we point to different objects, the methods they call are also polymorphic.

When you create an object of this class, the method called is the method of this class

When creating a subclass object, the method called is a subclass overridden method or an inherited method

Note when using polymorphism: if we write a unique method in the subclass (there is no method inheriting the parent class), the method cannot be called through the subclass object created by the reference of the parent class!

Note: inheritance is the basis of polymorphism.

C, reference type conversion

After understanding the meaning of polymorphism, we often need to do reference type conversion when using the features of polymorphism on a daily basis.

Reference type conversion:

1. Upward type conversion (implicit / automatic type conversion), which is the conversion of small types to large types

As illustrated by the above parent class Animal and a subclass Dog, when the reference of the parent class can point to the object of the subclass, it is up-cast. Such as:

two。 Downward type conversion (cast) is the conversion of large types to small types (there is a risk that data overflows may occur).

Add one line to the above code, and we convert the parent class to a subclass reference again, and the compiler does not allow us to do this directly, although we know that the superclass reference points to the subclass object. but the compiler believes that this conversion is risky. Such as:

So how do we solve this problem? we can add (Dog) before animal to force the cast. Such as:

However, if the parent class reference does not point to the object of the subclass, you cannot convert the type downwards, although the compiler will not report an error, but the program will make an error at run time, such as:

In fact, this is that the reference of the subclass mentioned above points to the object of the parent class, and the cast type cannot be converted!

There is also a situation where a reference to a parent class points to an object of another subclass, so it cannot be forcibly converted to an object of that subclass. Such as:

This is because we cast the type when compiling, and the type at compile time is the type we cast, so the compiler will not report an error, and when we run, the program opens up the memory space of the Dog type for animal, which does not match the memory space of the Cat type, so it cannot be converted normally. The nature of errors in these two situations is the same, so we should pay special attention to these two errors when using cast! Here is a safer way to achieve downward type conversion. no, no, no. no, no, no.

3. Instanceof operator to solve the type of reference object and avoid the security problem of type conversion.

Instanceof is a binary operator of Java, and = =, >, int-> long-> double->.. / / when there is no method corresponding to the basic type, it is boxed automatically and the wrapper class method is called. / / if there is no wrapper class method, the method of the interface implemented by the wrapper class is called. / / finally, call the char... that holds multiple parameters Method. A.eat ('a'); a.eat ('a`);} public void eat (short I) {System.out.println ("short");} public void eat (int I) {System.out.println ("int");} public void eat (double I) {System.out.println ("double");} public void eat (long I) {System.out.println ("long") } public void eat (Character c) {System.out.println ("Character");} public void eat (Comparable c) {System.out.println ("Comparable");} public void eat (char... C) {System.out.println (Arrays.toString (c)); System.out.println ("...");} / public void eat (char I) {/ / System.out.println ("char"); / / at this point, I believe you have a deeper understanding of the "three object-oriented features of Java". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report