Java Basic Learning note Five object-oriented Java basic syntax

Source: Internet
Author: User
Tags ming modifier

Object-oriented understanding of what is process oriented, object oriented

Process-oriented and object-oriented is a way of thinking in our programming, writing programs.
The process-oriented programming approach is the process of thinking "what should I do" when encountering one thing, and then implementing it step-by-step.
For example: Company cleaning (wipe glass, sweeping, mopping, garbage, etc.), in accordance with the process-oriented programming approach will think "cleaning how I do, and then a piece of the completion", finally the company clean up the health.
Object-oriented programming, is to meet one thing, think "I should let who do", and then that "who" is the object, he will do this thing is his own thing, anyway, the last group of objects together can be good on the line.
For example, the company to clean (wipe glass, sweeping, mopping, garbage, etc.), in accordance with the object-oriented programming method will think "I should let who do, such as Xiao Ming wipe glass, Jean Xiaoli sweep, let small Guo drag the ground, let Xiao Qiang trash, etc.", here "Xiao Ming, Xiao Li, Xiao Guo, Xiao Qiang" is the object How to clean is their own business, anyway, the last group of objects together to clean up the company's health.

Object-oriented examples

Buy computer (group installed)
Use the process-oriented instructions to buy a computer: Internet query parameters and quotations, Computer City inquiry, installation and supervision on site, hold the computer home. We are involved in every detail throughout the process and feel rather tired.
Using object-oriented instructions to buy a computer: If we need to buy an assembly machine, we should find someone who understands the computer hardware, let him help us to view the parameters and quotations, and make inquiry and bargain, as well as on-site assembly supervision. And we do not need to personally experience the specific how to do, just tell this person we want the specific needs can be. Analysis of the entire process, found that the moment becomes very easy, as long as the computer hardware to find the person, our problems can be solved. And we don't have to work so hard in this process.

The benefits of an object-oriented approach to thinking

After the use of object-oriented analysis through real-life scenarios, we begin to analyze the process-oriented and object-oriented differences to make a summary:

    • Object-oriented Thinking mode is a kind of thought which is more accord with people's thinking habit.
    • The process-oriented way of thinking is more of the embodiment of the executor (self-doing things), object-oriented more embodiment is the conductor (directing objects to do things).
    • The object-oriented way of thinking simplifies complex problems.
The use of classes and object objects in requirements

With an understanding of object-oriented, let's say how to use object-oriented to analyze problems and how to use object-oriented in specific problems.
We analyzed the elephant in the refrigerator as an example. In response to specific needs, the method of noun refinement can be used to analyze and find specific objects.
Need: Put the elephant in the refrigerator
Objects: Elephants, refrigerators
In three steps:

    • 1. Open the refrigerator door
    • 2. Put the elephant in
    • 3. Close the refrigerator door

The analysis found that opening, loading and closing are all functions of refrigerators. That is, the refrigerator object has the following functions:
Refrigerator Open
Refrigerator storage
Refrigerator off
Described in pseudo-code, there are two specific things in the above requirements Elephant and refrigerator
Description Elephant:

class Elephant {}

Description refrigerator

class Refrigerator {    void  open () {}    void  Storage (elephant) {}    void  closed ( ){}}

When specific things are described, it is necessary to use these specific things, and Java uses specific things that require the new keyword to create concrete instances of this thing.

Working with objects:
1. Create a Refrigerator object

New

2, call the function of the refrigerator

object. function (); bx. open (); bx. Storage (new  Elephant ()); Bx. Off ();

Summarize:

1, first in accordance with the terminology of the object of the problem areas
2, the object is described, in fact, in the clear object should have the attributes and functions
3. You can create a specific object of this thing by means of new
4. Call the function after it through the object.

The embodiment of the object in the code

In the analysis of real-life things, it is found that these things have their specific characteristics and functions, these features and functions constitute this special thing.
For example, describe a car:

    • Analysis:
    • The characteristics of a Thing (attribute):
    • Color.
    • Number of tires.
    • (function) of a thing:
    • Run.

It can be found that things are actually made up of features (attributes) and behaviors (functions).
It is simple to understand that a property is a numerical value, which is actually a variable, and a function is a method.

car {    color;    number of tires;    run () {    }}

This thing is described in computer language java.

To define the format of a class

 Public class class Name {    // can write 0 to n attribute     data type variable name 1;    data type variable name 2;    //  You can write 0 to n method     modifiers that return a value type method name (parameter) {        EXECUTE statement;    }}

Automobile class

 Public class Car {    String color;     int Number ;     void run () {        + ":" + number );}    }

By describing the code, you know that the real meaning of the class is to describe things. Attributes and functions are collectively referred to as members of a thing.

The members of a thing are divided into two types: member properties and member functions.
Member properties are represented in code as member variables, and member functions are reflected in code as member methods
Test the written code. Requires a class that can run independently.
Create the format of the object: Class Name Object name = New class name ();
Test class

 Public classCardemo { Public Static voidMain (string[] args) {/** Test: The Run method in the car class. *///1, create an object for car. Give the object a name. Car C =NewCar ();//c is a variable of class type. C points to an object of a specific car type. //2, the function of the object is called through an existing object. Format: Object. Object member;//3, you can assign a value to the property of the object. C.color = "Red"; C.number= 4;    C.run (); }}

Memory plots for objects

The difference between classes and objects

The object-oriented programming idea tries to keep the description of things in the program consistent with the shape of the things in reality. In order to do this, the object-oriented idea presents two concepts, namely, classes and objects. The class is an abstract description of a certain kind of thing, and the object is used to represent the individual of that kind of thing in reality. The next step is to use a legend to abstract the relationship of the class to the object, as shown in.


In, the toy model can be seen as a class, a toy as an object, from the toy model and the relationship between the toy can be seen between the class and the relationship between the object. Class is used to describe common characteristics of multiple objects, which are templates for objects. An object is used to describe an individual in reality, which is an instance of a class. It is obvious from this that the object is created from the class, and that a class can correspond to multiple objects, and then the classes and objects are explained separately.
Through the previous knowledge points of learning, basically mastered the class is used to describe things, classes can define the properties and behavior of things. The object is created using the New keyword by describing the class, and it is possible to invoke the object's specific properties and functions through the object.

Differences between local variables and member variables

What is the difference between a variable defined in a class and a variable defined in a method?
Difference One: the location of the definition is different
A variable defined in a class is a member variable; A variable defined in a method or in a {} statement is a local variable.
Difference two: The location in memory is different
Member variables are stored in objects that are in memory, and local variables are stored in the stack memory method
Difference three: The declaration period is different
The member variable appears in the heap as the object appears, disappearing from the heap as the object disappears; Local variables appear in the stack as the method runs and disappear with the stack of methods
Difference Four: Initialize different
Member variables have default initialization values because they are in heap memory, and local variables do not have default initialization values and must be assigned manually before they can be used.

Basic types and reference types are passed as parameters

Is there a difference between reference type data and basic type data as parameters? We use the following code to illustrate:

class demo{    publicstaticvoid  main (string[] args)    {        int x = 4;        Show (x);        System.out.println ("x=" +x);    }      Public Static void Show (int  x)    {        = 5;    }}    

When a primitive type is passed as a parameter, it is actually copying the value in the basic type variable x space to the Calling method Show (), and when x is copied in the show () method and the X variable is manipulated in the show () method, only the X in Show is affected. When the Show method executes, the program returns to the main method after the stack, and the X value in the main method is the original value.

 class   demo{ int   X;  public  static  void   main (string[] args) {Demo d  = n        EW   Demo ();        D.x  = 5;        Show (d);    System.out.println ( "x=" +d.x);  public  static  void   show (Demo d) {d.x  = 6

when a reference variable is passed as a parameter, it is actually a copy of the memory address (reference) in the reference variable space to the D reference variable passed to the Show method. At this point there will be two references pointing to the same object in the heap. When you execute d.x=6 in the Show method, the objects in the heap are found based on the reference held by D, and the value of its X property is changed to the 6.show method stack. since the two references point to the same object, no matter which reference changes the value in the referenced object, the other reference is used again as the changed value.

Encapsulation Package Overview

Encapsulation, it is also one of the characteristics of object-oriented thinking. An object-oriented total of three features: encapsulation, inheritance, polymorphism.
Package Performance:

    • Method is one of the most basic packages.
    • A class is actually a package.

From the above two points, the benefits of encapsulation are as follows:

    • Improved reusability of code.
    • It hides the implementation details and provides a way to access it externally. Facilitates the use of callers. This is one of the core, and can be understood as the concept of encapsulation.
    • Improved security.

Package examples
A computer, it is by the CPU, motherboard, graphics card, memory, hard disk, power and other parts of the team leader, in fact, we will assemble these parts together can use the computer, but found that these parts are scattered in the outside, very can cause unsafe factors, so, use the chassis shell, the components are installed in the inside, And in the case of the chassis left some sockets, if not left the socket, we think what will be the situation. Summary: In fact, the chassis is to hide the details of the card equipment, external provides the socket and switches and other access to internal details of the way.

Proprietary private

Understanding the encapsulation in the life of the embodiment, but also back to Java, in detail encapsulated in the Java code embodiment, first from the description of the person mentioned.

classPerson {intAge ;    String name;  Public voidShow () {System.out.println ("Age=" + Age + ", name" +name); }} Public classPersondemo { Public Static voidMain (string[] args) {//Create Person ObjectPerson p =NewPerson (); P.age=-20;//Assigning a value to a person objectP.name = "Shemale"; P.show (); //call person's Show method    }}

From the code above, although we describe the person in Java code clearly, there is a serious problem, that is, the behavior of the attributes of the man can be arbitrarily accessed and used. This is clearly not in line with actual needs.

But how can we not allow access? Need to use a keyword in Java is also a modifier private (private, permission modifier). As long as the attributes and behavior of the person are private, you cannot access them directly.

class Person {    privateint  : Age    ; Private String name;      Public void Show () {        System.out.println ("age=" + Age + ", name" + name);}    }

Age has been private, the wrong value can not be assigned, but the correct value can not be assigned, this still does not, that swollen do it? In accordance with the principle of encapsulation previously learned, after hiding, you also need to provide access methods. Let other programs access these methods as long as you provide accessible methods to the outside. The data can also be validated in the method.

General access to member properties: Assign (set), take a value (get get), so the way to access the private variable can provide a corresponding setxxx or GetXXX method.

classPerson {//Private member Variable    Private intAge ; PrivateString name; //provides methods for setting member variables externally     Public voidSetage (inta) {//since the value of the member variable is set, validation of the data can be added here        if(A < 0 | | a > 130) {System.out.println (a+ "age-inconsistent data range"); return; } Age=A; }    //provides methods for accessing member variables externally     Public voidGetage () {returnAge ; }}

Summary: content that is not required to be provided externally in a class is privatized, including properties and methods. After describing things later, properties are privatized and provided with Setxxx getxxx methods to access them. Note: Private is only the embodiment of the package.

this keyword

The question of the same name as the member variable and the local variable, when the local variable and the member variable have the same name in the method, then how to distinguish the local variable member variable in the method? You can distinguish member variables from local variables by adding this to the name of the member variable.

classPerson {Private intAge ; PrivateString name;  Public voidspeak () { This. Name = "Xiao Qiang";  This. Age = 18; System.out.println ("Name=" + This. Name + ", age=" + This. Age); }}classPersondemo { Public Static voidMain (string[] args) {person P=NewPerson ();    P.speak (); }}
memory interpretation of the object

We have learned how to use the Java code Description of things in life, and then we analyze the allocation of objects in memory. Here, we need to draw a step-by-step demonstration and follow the drawing process to explain the memory object creation process.

classPerson {Private intAge ;  Public intGetage () {return  This. Age; }     Public voidSetage (intAge ) {         This. Age =Age ; }} Public classPersondemo { Public Static voidMain (string[] args) {person P=NewPerson (); P.setage (30); System.out.println ("Hello everyone, this year I" + p.getage () + "old"); }}

The use procedure for creating a Memory object in a program.

Program execution Process Description:

    • 1. First execute the Main method (press stack), execute the person p = new person ();
    • 2, space in the heap memory, and allocate memory address 0x1234, followed by the member variable default initialization (age = 0); Assign memory address 0x1234 to the person p variable in the stack
    • 3, continue to execute the P.setage (30) statement, this will call the Setage (int age) method, 30 is assigned to the "age" variable in the Setage method; Execute this.age = Age statement, and the age variable value 30 Assign a value to the member variable this.age to 30;
    • 4. After the Setage () method is executed (stack), return to the main () method, execute the OUTPUT statement System.out.println (), and the console prints the age value in the P object.

Attention:
What does this mean? This represents the object, which is the specific object? Which object invokes the method in which this is located, and this represents which object.
In the P.setage (30) statement in the preceding code, the This in the setage (int age) method represents the P object.
The application of this
After studying the use of this, do a little practice now. Requirement: Define the function in the person class to determine whether two people are peers.

classPerson {Private intAge ; PrivateString name;  Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public voidspeak () {System.out.println ("Name=" + This. Name + ", age=" + This. Age); }    //determine if you are a peer     Public Booleanequalsage (person p) {//compare with the age of the Equalsage method object that is currently called and the Age passed in P//since it is not possible to determine which object is calling the Equalsage method, this can be used instead/** if (this.age = = P.age) {return true;} return false;*/        return  This. Age = =P.age; }}

Java Foundation Learning note Five object oriented Java basic syntax

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.