Notes on learning the basic concepts of object-oriented programming in Java

Personally, the so-called class in programming is the same concept as the class in the classification of objects in the real world, but it is borrowed in programming. Class represents things with a series of commonalities and the same operation or action, which is an abstract data type in programming. Each specific individual (in the real world) and instance variable (for programming) are objects.

A class is a representation of the common characteristics (properties and operations) of some objects in the real world, and an object is an instance of a class.

Class attribute: it is the abbreviation of the static attribute of a class. It refers to the data contained in the class, such as variables or objects of other classes; Class: is called a member function or method.

¨ 

Classes in Java are defined as follows:

Let's talk about each part in detail:

Before the class keyword, that is, class modifiers can be divided into three types: access modifier, public class, final modifier (final class specifier) and abstract modifier (abstract class specifier)

Among them, the permission modifier can only be public or default (that is, empty, nothing, which means that it is defined as friendly). Public means that this class can be used and accessed anywhere (as long as the program can find the location of this class), whether in the same package or in different packages. Note that this is different from C + +. In C + +, there is no modifier to restrict the access rights of classes, but a description of the inheritance relationship between classes. In addition, they all restrict the access rights of class properties and methods. The default access permission (defined as friendly) means that it can only be referenced and accessed by classes in the same package, but not by classes in other packages, even if imported.

It will also be mentioned later: when using the default modifiers of class properties and methods, it is also indicated that it can only be referenced and accessed by classes in the same package.

Multiple inheritance is not allowed in Java, which is different from C + +. In order to make up for this deficiency, the concept of interface is introduced in Java.

In the definition of the above class, the class body mainly includes the specific content of the class, including the properties and methods of the class. The properties of a class can be simple variables or instances of some classes. If it is an instance of a class, it can be defined as follows:

[modifier] class name object name = new class name (parameter list);

When declaring objects and complex variables, they can not be created at the time of declaration, but can be created in future constructors.

The methods defined in a class usually play two roles: one is to carry out various operations around the properties of the class; The second is to conduct data exchange, message passing and other operations with other classes or objects.

The syntax for declaring methods in Java is as follows:

Class methods, also known as member functions, are used to specify the operations on class attributes and the mechanism to realize the internal functions of the class. At the same time, they are also an important window for the class to interact with the outside world.

Java programmers pay attention to creating user-defined types called classes. Classes are also called programmer defined types. Each class contains data and a set of methods to manipulate data. The data part of the class is called instance variables. Instances of user-defined types (i.e. classes) are called objects.

An object is an instance of a class. A class is an abstraction of the same object and a template for creating an object. Creating an object in a program will open up a space in memory, including the properties and methods of the object. Create objects using the keyword operator new.

Constructor (it can be compared with C + +, which is almost the same as C + +)

Create your own constructor • the constructor name is the same as the class name. When constructing the object of the Employee class, this constructor is started and the instance field is assigned an initial value. In Java, the definition and initialization are unified -- both are indispensable. For example, when you create an instance of the Employee class with the following code,

newEmployee (“James Bond”,100000,1950,1,1);

Constructor features:

(1) Constructor and class have the same name.

(2) A class can have multiple constructors.

(3) Constructors can have 0, 1, or more parameters.

(4) Constructor has no return value.

(5) Constructors are always called with the new operator.

Function of constructor (1) object initialization

(2) Introduce more flexibility (variable assignment or more complex operations)

(3) Constructors can not be defined in Java

You can not define a constructor in Java. At this time, the system will automatically generate a default constructor for the system. This constructor has the same name as the class name. It has no formal parameters and does nothing.

Method overview Java programs are composed of class definitions. Classes have two parts: properties and methods. Properties describe what the class is and methods describe what the class does. Any object has separate memory to store its properties. All objects of the class share methods stored in memory.

In other words: methods are the main part of a class. In a class, the function of the program is embodied in the method.

Method is to create a named subroutine in Java. A main method and several sub methods. The main method calls other methods, and other methods can also call each other. The same method can be called by one or more methods any time. Defining another method in one method will result in a syntax error.

(1) It is best to avoid "shielding" instance variables by local variables. This can be done without using identifiers with the same name in a class; parameters in method calls are used to pass values and references, and methods can also be nested and recursive. (2) If a non void return value type is specified in the method body, the method must contain a return statement to ensure that there is a return value in any case, and the return statement cannot be followed by any expression. The basic structure of the Java program is as follows:

Java introduced the concept of "access control modifier", which allows the library creator to declare what can be used by customer programmers and what can not be used.

The level of access control is between "maximum access" and "minimum access", including: public, "default" (no keyword), protected and private. The following list describes the meaning of access control modifiers:

The public access control character public is used for the following classes:

There is only one access control character of a class in Java: public, that is, public. A class is declared as a public class, indicating that it can be accessed and referenced by all other classes. Access and reference here means that the class is visible and usable as a whole. Other parts of the program can create objects of this class, access visible member variables inside this class and call its visible methods. A class as a whole is visible to other parts of the program, which does not represent all properties and methods in the class. At the same time, it is also visible to other parts of the program. The former is only a necessary condition for the latter. Whether the properties and methods of the class can be accessed by all other classes depends on their own access control characters.

For in class properties:

The in class attribute decorated with public is called public attribute. If this class is public, it can be accessed by all other classes.

Default access control characters are used for classes

If a class has no access control character, it has the default access control feature. This default access control specifies that this class can only be accessed and referenced by classes in the same package, and can not be used by classes in other packages. This access feature is called package accessibility. By declaring the access control character of the class, the whole program structure can be clear and rigorous, and the possible inter class interference and errors can be reduced.

For class properties

If the attributes and methods in the class are not qualified by access control symbols, they also have package accessibility.

3 private access control character private the property or method modified with private can only be accessed and modified by the class itself, and can not be obtained and referenced by any other class, including its subclasses. 1) Private data, for example, has three instance fields that contain data that is manipulated within an instance of the Employee class.

private string name;

private double salary;

private Date hireDay;

The private keyword is used to ensure that only the methods of the Employee class itself can access these instance fields.

2). When implementing classes for private methods, we make all data fields private because exposed data is dangerous. What about the method? Although most methods are public, private methods are often used. These methods can only be separated by the same method.

In general, private methods can be selected in the following cases:

(1) Methods that are independent of the user of the class.

(2) If the implementation of the class changes, those methods that are not easy to maintain.

Protected the member variable modified with protected can be referenced by three types: the class itself, other classes in the same package with it, and subclasses of the class in other packages. The main purpose of using the protected modifier is to allow its subclasses in other packages to access the specific properties of the parent class. The protected keyword introduces a concept called "inheritance", which is based on existing classes and adds new members to them, At the same time, it will not affect the existing class - we call this existing class "base class" or "base class". It can also change the behavior of the existing members of that class. For inheritance from an existing class, we say that our new class "extends" the existing class

The private protected access control characters private protected and protected are used together in order to form a complete access control character: private protected access control character. Member variables modified with privateprotected can be accessed and referenced by two types: the class itself and all subclasses of the class, whether these subclasses are in the same package as the class or in other packages.

Compared with protected, the privateprotected modifier excludes the non subclasses in the same package from the accessible scope, making the member variables more specific to the classes with explicit inheritance relationship, rather than the packages loosely combined.

Static modifier static is called static modifier, which can modify properties and methods in a class.

Using the static keyword can meet two requirements:

(1) One case is that you only want to use one storage area to store a specific data - no matter how many objects you want to create, or even no objects at all; the attributes modified by static are called static attributes. One of the most essential characteristics of these attributes is that they are attributes of a class, not specific objects of any class. In other words, they are specific to any one of the class As for a body object, a static attribute is a public storage unit. When an object of any class accesses it, it gets the same value. Similarly, when an object of any class modifies it, it is also operating on the same memory unit. (2) Another situation is that we need a special method that is not associated with any object of this class, that is, even if no object is created, we need a method that can be called directly with the class.

An important use of static is to help us call that method without having to create an object.

Static constants static variables are rare. However, static constants are common. For example, the math class defines a static constant: public class math

Static method declaring a method as static has at least three meanings: (1) when using this method, you should use the class name as the prefix instead of a specific object name; (2) A non static method is a method belonging to an object. When the object is created, the object's method has its own special code segment in memory; while a static method belongs to the whole class, and its code segment in memory will be allocated and loaded with the definition of the class and will not be exclusive to any object; (3) Because the static method belongs to the whole class, it cannot manipulate and process the member variables belonging to an object, but can only process the member variables belonging to the whole class.

5 main methodthe main method does not operate on any object. In fact, when the program starts executing, there are no objects. Static methods are executed and objects required by the program are constructed.

Tip: each class can have a main method. This is a convenient technique for unit testing classes.

Abstract is an abstract modifier that can be used to modify a class or method.

Abstract class when a class is declared abstract, the class is called abstract class. An abstract class is a class without a concrete instance object. To solve this problem, Java specifically provides a mechanism called "abstract method". It is an incomplete method with only one declaration and no method body. The following is the syntax used for abstract method declaration: Abstract void x();

Abstract method is used as class method modifier, and abstract declares an abstract method with only method header but no concrete method body and operation implementation.

It can be seen that the abstract method only has the declaration of the method header, and uses a semicolon to replace the definition of the method body: as for the specific implementation of the method body, it is completed by different subclasses of the current class in their respective class definitions. It should be noted that all abstract methods must exist in the abstract class

Yes. In addition to abstract methods, abstract classes can also have specific data and methods. Abstract method is a very important concept in Java programming language. You will use it a lot in the interface. Note: it is necessary to compare and remember with the interface. The methods in the interface belong to abstract methods. Of course, the interface also has attributes, and their specific properties will be described in detail later.

Final class, final attribute, final method and Terminator (there may be no final modifier in C + +)

Final is the final modifier that modifies classes, properties, and methods. In addition, the keyword of terminator is very similar to final, which will be introduced together

Final class

If a class is declared final, it means that it can no longer derive new subclasses and cannot be inherited as a parent class. Therefore, a class cannot be declared both abstract and final.

Classes defined as final usually have special functions and are used to complete standard functions. Defining a class as final can fix its contents, attributes and functions and form a stable mapping relationship with its class name, so as to ensure that the functions implemented when referencing this class are accurate

Finally, many programming languages have their own way to tell the compiler that a certain data is a "constant". Constants are mainly applied to the following two aspects:

(1) Compile time constant, which will never change;

(2) A value initialized at run time that we do not want to change.

An instance field can be defined as final (immutable). This field must be initialized when the object is constructed. That is, you must ensure that the value of each constructor has been set before it ends. The value of the field cannot be changed later

The final method may be used for two reasons. The first is to "lock" the method to prevent any inherited class from changing its original meaning. When designing a program, you can do this if you want the behavior of a method to remain unchanged during inheritance and cannot be overwritten or rewritten. The second reason for adopting the final method is the efficiency of program execution

Finalizer a finalizer is a method that executes when an object is reclaimed. Similar to the constructor, which is the method executed when creating an object. example

Other modifiers

volatile

If a property is modified by volatile, it means that this property can be controlled and modified by several threads at the same time.

synchronized

It is mainly used for thread synchronization

native

Indicates that the method is not written in Java language (it is written in C, C + +, etc.)

A little information found on the Internet: -- internal class

In short, an internal class is a class in a class. For example:

Here, B is the internal class of A. the feature of the internal class is that it can easily access the private methods and properties in the external class. For example, B can directly access the private property I and private method m () in a

The most important characteristics of object-oriented programming are encapsulation (also known as abstraction), inheritance and polymorphism. As an object-oriented programming language, Java has its advantages in this regard:

"Inheritance is a form of software reuse, which is effective in reducing software complexity. Inheritance is also the characteristic of object-oriented programming language. The language using object but without inheritance is an object-based language, but not an object-oriented language, which is the difference between the two."

The inheritance relationship between classes is a direct simulation of the genetic relationship in the real world. It represents the internal relationship between classes and the sharing of attributes and operations, that is, subclasses can follow some characteristics of the parent class (inherited class). Of course, subclasses can also have their own independent attributes and operations

Inheritance is a form of software reuse. New classes are generated from existing classes. By retaining their properties and behaviors, and modifying the performance according to the requirements of the new class, new properties and behaviors are added. If a subclass inherits from only one parent class, it is called single inheritance; If a subclass inherits from more than one parent class, it is called multi inheritance. Note that Java does not support multiple inheritance, but it supports the concept of "interface". Interface enables Java to obtain many advantages of multiple inheritance and abandon the corresponding disadvantages. Note: C + + supports multiple inheritance

Definition of inheritance relationship:

Parent class name followed by extensions

Keyword is used to indicate which subclass of the existing class the current class is, and there is an inheritance relationship.

Define two subclasses of the Employee class Employee:

General employee: commonemployee

Supervisor class: manageremployee

There are two main aspects of subclass inheritance from parent class:

(1) Property inheritance. For example, a company is a parent class, and a company has a name, address, manager, employee, etc., all of which belong to the structural aspect.

(2) Method inheritance. A parent class defines several operations. For example, a company must have operations such as project, profit, manager appointment, employee employment, etc. the subsidiary company will also inherit these behaviors s; MP

Property inheritance and hiding although the Employee class is a parent class, it does not mean that it has more functions because it is a parent class. On the contrary, children have more functions than their parents. Because the subclass is an extension of the parent class, it adds properties and methods that the parent class does not have. (1) the subclass cannot access the private member of the parent class, but the subclass can access the public of its parent class,

(2) Protected access is a protective intermediate level between public and private access.

(3) Because the inherited parent class members are not listed in the subclass declaration, but these members do exist in the subclass. Here, we should distinguish the confusing concepts of inheritance, overwrite and overload:

Only at the conceptual level of method can these three concepts be easily confused:

Method inheritance

For subclass objects, you can use the methods in the parent class. Even if these methods are not explicitly defined in the subclass, they are automatically inherited from the parent class

Method coverage

Method coverage refers to that a subclass defines a method with the same name to cover the method of the parent class. It is an implementation of polymorphism technology. When a parent method is overridden in a subclass, the subclass version usually calls the parent version and does some additional work.

There are many precautions. Here, I mainly mention this and super. There is this in C + + (and the concept is similar to that in Java), but there is no super.

This represents the current object itself, and this represents a reference to the current object. Can be understood as another name of the object. Using this, you can call the methods and properties of the current object.

For example: this Getname () and getname () are the same in the class.

Super refers to the direct parent object of the current object and the reference method overload of the parent object of the current object

Definition of overload: methods can be defined with the same method name but different parameter tables (the number, type or order of parameters in the parameter table are different), which is called method overload. • overload (overloading): overloading occurs when multiple methods have the same name and different parameters. The compiler must choose which method to call. It selects the correct method by comparing the parameter types in different method headers with the types of values used in a specific method call.

Polymorphism allows existing variables and related classes to be handled in a unified style, making it easy to add new functions to the system. Here, the information found on the Internet can more clearly clarify the polymorphism and problems in inheritance that need special attention:

Java's polymorphism object-oriented programming has three characteristics: encapsulation, inheritance and polymorphism.

Encapsulation hides the internal implementation mechanism of the class, which can change the internal structure of the class without affecting the user, and protect the data at the same time.

Inheritance is to reuse parent code and prepare for polymorphism. So what is polymorphism?

Method rewriting, overloading and dynamic connection constitute polymorphism. One of the reasons why Java introduces the concept of polymorphism is that it is different from C + + in class inheritance. The latter allows multiple inheritance, which does bring it very powerful functions, but the complex inheritance relationship also brings more trouble to C + + developers. In order to avoid risks, Java only allows single inheritance, There is an is-a relationship between the derived class and the base class (i.e. "cat" is a "animal") )。 Although this ensures that the inheritance relationship is simple and clear, it is bound to have great functional limitations. Therefore, Java introduces the concept of polymorphism to make up for this deficiency. In addition, abstract classes and interfaces are also important means to solve the limitations of single inheritance. At the same time, polymorphism is also the essence of object-oriented programming.

To understand polymorphism, we must first know what is "upward transformation".

I have defined a subclass cat, which inherits the animal class, so the latter is the former and is the parent class. I can pass

Instantiating a cat object is not difficult to understand. But when I define it this way:

What does that mean?

Very simple, it means that I have defined a reference of animal type, pointing to the newly created cat type object. Since cat inherits from its parent class animal, references of animal type can point to objects of cat type. So what's the point? Because a subclass is an improvement and extension of the parent class, the general subclass is more powerful in function and more unique in attributes than the parent class,

Defining a reference of a parent class type to an object of a subclass can not only use the powerful functions of the subclass, but also extract the commonalities of the parent class.

Therefore, the reference of the parent type can call all the properties and methods defined in the parent class, but it has no choice for the methods defined in the child class but not in the parent class;

At the same time, a method in the parent class can be called by the reference of the parent type only if it is defined in the parent class and not overridden in the child class;

For the method defined in the parent class, if the method is overridden in the child class, the reference of the parent type will call the method in the child class, which is dynamic connection.

Look at the following procedure:

The above program is a typical example of polymorphism. The child subclass inherits the parent class father, overloads the func1 () method of the parent class, and overrides the func2 () method of the parent class. The overloaded func1 (int i) and func1 () are no longer the same method. Since there is no func1 (int i) in the parent class, the reference child of the parent class type cannot call the func1 (int i) method. If the subclass overrides the func2 () method, the child referenced by the parent class will call the overridden func2 () in the subclass when calling the method.

So what results will the program print?

Obviously, it should be "CCC".

For polymorphism, it can be summarized as follows:

(1) Use the reference of the parent type to point to the object of the child class (actual object);

(2) The reference can only call the methods and variables defined in the parent class;

(3) If a method in the parent class is overridden in a subclass, the method in the subclass will be called when calling the method; (dynamic connection and dynamic call) (4) variables cannot be overridden (overwritten). The concept of "Rewriting" is only for methods. If a variable in the parent class is "rewritten" in a subclass, an error will be reported during compilation.

Polymorphism is realized by: (1) interface and several different classes that implement the interface and cover the same method in the interface; (2) parent class and inherit the parent class and cover several different subclasses of the same method in the parent class

1. Basic concepts

Polymorphism: Send a message to an object and let the object decide what behavior to respond to. Dynamic method calls are implemented by assigning subclass object references to superclass object reference variables.

This mechanism of AVA follows a principle: when a superclass object references a subclass object with a reference variable, the type of the referenced object rather than the type of the reference variable determines whose member method to call, but the called method must be defined in the superclass, that is, the method overridden by the subclass.

(1) If a is a reference to class A, a can point to an instance of class A or a subclass of class A. (2) if a is a reference to interface a, a must point to an instance of a class that implements interface a.

Java polymorphism implementation mechanism

Sun's current JVM implementation mechanism, The reference of a class instance is a pointer to a handle. This handle is a pair of pointers: a pointer points to a table. In fact, the table also has two pointers (one pointer points to a method table containing an object, and the other points to a class object, indicating the type of the object); the other pointer points to a piece of memory space allocated from the Java heap.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>