I. Basic concepts of Object-Oriented Java

Source: Internet
Author: User

1. Object-oriented

Object Oriented is an emerging programming method, or a new program design specification (paradigm ), the basic idea is to use objects, classes, inheritance, encapsulation, polymorphism and other basic concepts for program design. Construct a software system based on objective things (objects) in the real world, and use human natural thinking methods as much as possible in system construction.

What is OOP?

OOP is the programming of surface image objects and is a programming method relative to structured programming. It is not difficult to understand structured programming. Simply looking at the world around you, you can find the characteristics of OOP.

For example, a car with basic equipment such as wheels and engines can provide basic functions for driving. As a user, we don't need to know the specific construction details of the car, as long as we know how to operate the steering wheel and let the car go.

That is to say, to achieve the goal, we only need to acquire an object and know how to use it. We do not need to pay attention to the specific implementation details.

For example, to assemble a car, you need a lot of parts. All of these parts have certain specifications and can complete a specific function. For example, the engine generates power, and the brakes are used for braking. Each part is combined to achieve a larger goal. These parts are the specific units to be studied.

In the above example, a car is the unit we need to use to achieve the purpose of travel, and an engine or brake pad is the unit we need to assemble a car. In the process of use, we only focus on the specifications and capabilities of the unit, rather than the specific operation details of the unit. In the programming world, these units can be abstracted as classes, that is, classes with certain attributes and behaviors.

2. Object

An object is an entity used to describe objective things in a system. It is a basic unit of a system. An object consists of a group of attributes and a group of services that operate on these attributes.

Class instantiation can generate an object. The lifecycle of an object consists of three stages: generation, use, and elimination.

When there is no reference to an object, the object becomes a useless object. The Java Garbage Collector automatically scans the dynamic memory area of the object and collects and releases the unreferenced object as the garbage collection. When the System memory is used up or the System. gc () is called to request garbage collection, the garbage collection thread runs synchronously with the System.

3. Class

A class is a set of objects with the same attributes and methods. It provides a unified abstract description for all objects belonging to the class. It contains two main parts: attributes and methods. In an object-oriented programming language, a class is an independent program unit. It should have a class name and contain two main parts: attributes and methods.

The class implementation in Java includes two parts: class declaration and class body.

Class Declaration

<Span style = "font-size: 18px;"> [public] [abstract | final] class className [extends superclassName] [implements interfaceNameList] {……} The modifiers public, abstract, and final indicate the class attributes. className indicates the class name, superclassName indicates the class parent class name, And interfaceNameList indicates the list of interfaces implemented by the class. ClassclassName {[public | protected | private] [static] [final] [transient] [volatile] type variableName; // member variable [public | protected | private] [static] [final | abstract] [native] [synchronized] returnType methodName ([paramList]) [throws exceptionList] {statements} // member method} </span>

Meanings of member variable qualifiers:

Static: static variable (class variable)

Final: constant; transient: temporary variable, used for object archiving, used for Object serialization

Volatile: Contribution variable for concurrent thread sharing

The implementation of the method includes two parts: Method description and method body.

Method Declaration

Meanings of qualified words in method declaration:

Static: class method, which can be called directly by Class Name

Abstract: abstract method, no method body

Final: The method cannot be overwritten.

Native: code that integrates other languages

Synchronized: controls the access of multiple concurrent threads

The method declaration includes the method name, return type, and external parameters. The parameter type can be either a simple data type or a composite data type (also called a reference data type ).

For simple data types, java implements value passing. Methods receive parameter values, but cannot change the values of these parameters. If you want to change the parameter value, you can use the reference data type because the referenced data type is passed to the address of the data in the memory. operations on the data in the method can change the value of the data.

Method body

The method body is the implementation of the method. It includes the declaration of local variables and all valid Java commands. The scope of the local variables declared in the method body is within the method. If the local variables have the same name as the class member variables, the class member variables are hidden.

To distinguish between parameters and class member variables, we must use this. This is used to reference the current object in a method. Its value is the object that calls this method. The return value must be the same as the return type, completely the same, or its subclass. When the return type is an interface, the return value must be implemented.

Constructor

Constructor is a special method. Every class in Java has a constructor to initialize an object of this class.

The constructor has the same name as the class name and does not return any data type.

Overloading is often used for constructor.

The constructor can only be called by the new operator.

4. Basic object-oriented features

Encapsulation

Encapsulation is to hide the internal details of an object as much as possible, form a boundary for external entities, and only retain limited interfaces and methods for external interactions. The principle of encapsulation is to prevent external access to and operation on the internal properties of objects, thus avoiding external damage to the internal properties of objects.

You can set certain access permissions for Class Members to hide member information in the class.

Private: a private member in a class. It can only be accessed by the class itself. If the constructor of a class is declared as private, other classes cannot generate an instance of the class.

Default: The members without any access permission restriction in the class belong to the default access status and can be accessed by the class itself and the class in the same package.

Protected: a member of a class that is limited to protected. It can be a member of the class itself and its subclasses (including subclasses in the same package and in different packages) and all other classes in the same package.

Public: Only public members in a class can be accessed by all classes.

Inheritance

The subclass object has all attributes and methods of the parent class, which is called the inheritance of the parent class by the subclass.

In Java, the parent class can have multiple subclasses, but the child class can inherit only one parent class, which is called single inheritance. Inheritance achieves code reuse. All classes in Java are obtained by directly or indirectly inheriting the java. lang. Object Class.

Subclass cannot inherit the member variables and methods whose access permission is private in the parent class.

Subclass can override the parent class method, that is, name a member variable with the same name as the parent class.

In Java, super is used to access the parent class members. super is used to reference the parent class of the current object. There are three scenarios for super:

Access hidden member variables of the parent class, such as super. variable;

Call the Method to be overwritten in the parent class, for example: super. Method ([paramlist]), super () call the parent class constructor;

Call the constructor of the parent class, for example, super ([paramlist]);

Polymorphism

Object polymorphism refers to the inheritance of attributes or methods defined in the parent class, which can have different data types or show different behaviors. This makes the same attribute or method have different semantics in the parent class and its sub-classes. For example, the "plotting" method of "ry", "elliptic" and "polygon" are both subclasses of" ry". The "plotting" method has different functions.

Java polymorphism is embodied in two aspects: static polymorphism implemented by method overloading (polymorphism at compile time) and dynamic polymorphism implemented by method rewriting (Runtime polymorphism ).

Polymorphism during compilation: during the compilation phase, the compiler determines which method is called to be overloaded.

Runtime polymorphism: subclass objects can be used as parent objects because they inherit all attributes of the parent class (except private ones. Any place in the program that uses the parent class object can be replaced by a subclass object. An object can call the subclass method by referencing the subclass instance.

Overloading)

Method Overloading is a means for classes to process different data types in a unified manner.

Multiple methods can be created in a class. They have the same name, but have different parameters and different definitions. When calling a method, you can determine the method to use by the number and type of different parameters passed to them.

The return value types can be the same or different, and the return type cannot be used as the criteria for distinguishing the overloaded functions.

Overriding)

Subclass re-writes the method of the parent class. If the method in the subclass has the same method name, return type, and parameter table as its parent class, we say this method is overwritten ).

If you need the original method of the parent class, you can use the super keyword, which references the parent class of the current class.

The access modification permission of subclass functions cannot be lower than that of the parent class.

 

Publicclass Human {// Human is the class name String name; // This is the definition attribute // This is the definition behavior public void speack (String words) {System. out. println (words );}}

<span style="font-size:18px;">HumanzhangSan = new Human(); </span>

In this way, the zhangSan person is created. HumanzhangSan is similar to int I. Focus on new Human ()


Class and constructor


When a specific object is instantiated by a class, the constructor will execute. For example, the Human class defines two constructor methods, one with no parameters and the other with parameters. See the constructor form-no return value.

<Span style = "font-size: 18px;"> publicclass Human {Stringid; // This is the unique attribute Stringname of the object; // This is new Human () the construction method Human () {}// this is the construction method Human (StringshenFenZheng) {id = shenFenZheng ;}</span> called when newHuman ("111111111 ")


NewHuman () is to call a construction method without parameters to create a Human instance object.

Class Method

A method is the support of a class action. All the methods of the class define the ability range of the class, and the specific implementation process is written in the content of the method. The method definition follows a certain format:

Modifier return value type method name (parameter type parameter name)

<span style="font-size:18px;">publicvoid speack(String words) </span>

In this example:

Modifier: public (later)

Return Value: void (null, that is, no return value)

Method Name: speak

Parameter type: String)

Parameter Name: words (this is the name of the variable within the method)

Class attributes and access methods

 

As one of the OOP principles: Data Hiding (or encapsulation ). The object attributes cannot be directly accessed by external objects, but should be completed through the get and set methods provided by the object itself.

<Span style = "font-size: 18px;"> publicString getName () {return name;} publicvoid setName (String aName) {name = aName; // The name here is the attribute in the class. All methods of this class can be directly accessed and assigned values} </span>

A more reasonable class

So far, we have all the fragments of a class. Let's splice them together:

<Span style = "font-size: 18px;"> publicclass Human {String id; // The attribute variable String name of the class; // attribute variable of the class // This is the constructor called when new Human () is Human () {}// this is new Human ("111111111 ") human (String shenFenZheng) {id = shenFenZheng;} public String getId () {return id;} public void setId (String shenFenZheng) {id = shenFenZheng ;} // Method for retrieving name content public String getName () {return name;} // Method for modifying name content public void set Name (String aName) {name = aName;} // class behavior public void speak (String words) {System. out. println (words) ;}} example: publicclass Meeting {public static void main (String [] args) {// a baby was born with Human zhangSan = new Human (); // an account is reported. The ID card number is zhangSan. setId ("1234567890123"); // The parent name is zhangSan. setName ("Zhang San"); // another baby is born with Human xiaoMing = new Human (); xiaoMing. setId ("3210987654321"); xiaoMing. setName ("James "); // The two met, and Zhang sanxian greeted zhangSan. speak ("Hello! I am "+ zhangSan. getName (); // out of courtesy, James replied xiaoMing. speak (" Hello! I'm "+ xiaoMing. getName () +", glad to meet you ") ;}}</span>


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.