Java Tour (iv)-object oriented thinking, member/local variables, anonymous objects, encapsulation, private, construction methods, building blocks of code

Source: Internet
Author: User

Java Tour (iv)-object oriented thinking, member/local variables, anonymous objects, encapsulation, private, construction methods, building blocks of code

Come on, it's going to be a little faster.

1. Overview

This is the length of the story, which focuses on the thought and the case

Take the buy computer, first, you do not understand the computer, you go to computer city to buy a computer, and elephant installed in the refrigerator, what is the step? Consulting bargaining, talk about the computer to leave, right, this is the process-oriented thinking, and object-oriented is: You have a friend, he knows the computer, what will, you just take him to, you can, you this buddy is the object, in Java, we are manipulating an object to complete a variety of operations, This is the object-oriented idea.

2. Member variables

There are three main characteristics of object-oriented

    • Packaging
    • Inherited

What exactly does that mean?
We develop the words that are looking for objects, without objects, the new object, objects and classes, objects and objects are related, we need to maintain

Class is the description of things in life.
The object is the entity in which such things exist.

Requirements: Describe the car (color, number of tires), describe things is to describe the properties and behavior of things
We can define a class directly

//public class class name Public  class Hellojjava {    //public static no return value the Main method array     Public Static void Main(string[] str) {Car car =NewCar ();//Output ColorSystem.out.println (Car.color +"The Car");//Output tires numberSystem.out.println (Car.num +"a wheel.");//Output behaviorCar.run (); }}/** * Auto Class * * @author LGL * * */Class Car {//ColorString color ="Red";//Number of tires    intnum =4;//Behavior    voidRun () {System.out.println ("I Am"+ Color +"The car, I have"+ num +"a wheel."); }}

So everyone can see, we monkey sister new a car will be able to

In fact, defining a class is describing things. is to define properties and behaviors, and attributes and behaviors become members of the class ( member variables )

3. Local Variables

In fact, we've been writing about local variables, and the difference between him and the member variables is that the scope of the action is different.

We take the above example

    • Member variables: Acting on the global
    • Local variables: Action in CAR class

In-memory storage and location

    • The member variable is in heap memory because the object exists in memory
    • Local variables in stack memory
4. Anonymous objects

This is a small knowledge point, anonymous in other words is actually no name meaning

    • Anonymous objects are simplified versions of objects
    • Two usage of anonymous objects
      • When only one call is made to an object method
      • An anonymous object can be passed as an actual parameter

Let's use a simple example

//正常的写法new5;//匿名对象new5;

You can see I don't have a name to change the value of Num directly, this is the anonymous object

The second way of using the actual parameters to pass, in fact, I used the

// 输出颜色System.out.println(new"的小汽车");

That's OK.

5. Encapsulation

OK, finally, we have the core idea encapsulation

Encapsulation meaning: Refers to the properties of hidden objects and implementation details, only provide access to external

Benefits

    • Separating the changes
    • Easy to use
    • Improved reusability
    • Improve security
The

Encapsulation principle

Hides content that is not required to be provided externally;
Hide properties, provide external access

We write an example

//Common class name  public  class  hellojjava  { //public static no return value the Main method array  public  static  void  main  (    String[] str) {showstring ( "I am Encapsulation" );    } /** * Package * * @param  STR */ public  static  void  showstring  (String str)    {System.out.println (str); }}

This is the simplest package, you give me a string I'll print, the process you don't have to know, the function itself is a minimal package

6.private

Private, how to use?

//公共的   类   类名publicclass HelloJJAVA {    // 公共的 静态 无返回值 main方法 数组    publicstaticvoidmain(String[] str) {        new Person();        20;        p.speak();    }}class Person {    int age;    // 说话方法    void speak() {        System.out.println("我今年""岁");    }}

Our current code is written in this way, and the result of the output

Here we have direct access to ARG, where there is a security risk, here is the use of the private modifier to modify ARG

Here, we see a false hint, because when we decorate with private, you can't get it.

Private: Proprietary, permission modifier: Used to decorate members in a class (member variables, member functions)
Note that the private is only valid in this class

So how do we get to the interview? Now that you're private, you need to provide a way out.

//public class class name Public  class Hellojjava {    //public static no return value the Main method array     Public Static void Main(string[] str) {Person p =NewPerson ();//p.age =;P.setages ( -);    P.speak (); }}class Person {//Private    Private intAge/** * External methods * * @param a * *     Public void setages(intA) {age = A; }//method of speaking    voidSpeak () {System.out.println ("I am this year"+ Age +"Old"); }}

We can do that, too.

But we don't usually do that, we have norms.

publicintgetAge() {        return age;    }publicvoidsetAge(int age) {        this.age = age;    }

So our complete code should be written like this.

//public class class name Public classHellojjava {//public static no return value the Main method array     Public Static void Main(string[] str) {Person p =NewPerson ();//p.age =;        //P.setages (+);P.setage ( -);    P.speak (); }}class Person {//Private    Private intAge Public int Getage() {returnAge } Public void Setage(intAge) { This. Age = Age; }//method of speaking    voidSpeak () {System. out. println ("I am this year"+ Age +"Old"); }}

Results of the output

But remember, note that private is only a form of encapsulation;

The reason we provide access is to facilitate us to join logical judgment statements, to manipulate the data accessed, to improve the robustness of the Code

7. Construction method

Characteristics

    • The function name is the same as the class name
    • Do not define return value types
    • You cannot write a return statement

Role

    • Initialize an object

Attention

    • Features of the default constructor
    • Multiple constructors exist in the form of overloads
//公共的   类   类名publicclass HelloJJAVA {    // 公共的 静态 无返回值 main方法 数组    publicstaticvoidmain(String[] str) {        new Person();    }}class Person {    //构造方法    publicPerson() {        System.out.println("我是构造方法");    }}

As soon as we get new, we're going to implement the construction method.

When an object is established, the corresponding constructor is called
function of the constructor: can be used to initialize an object
Small details of the constructor, when a constructor is not defined in a class, the system defaults to adding an empty argument construction method to the class
When the class defines a constructor method, the default is no, and the construction method uses the overloaded

//public class class name Public classHellojjava {//public static no return value the Main method array     Public Static void Main(string[] str) {Person p =NewPerson (); person P1 =NewPerson ("I am Millet"); person P2 =NewPerson ("I am Xiao Wang", -); }}class Person {//Construction method     Public  Person() {System. out. println ("I am the construction method"); }//Construction method     Public  Person(String str) {System. out. println (str); }//Construction method     Public  Person(String str,intAge) {System. out. println ("I am the construction method"+ age); }}

That's it, we output

8. Building Code Blocks

Here's a little bit of knowledge to end this space.
Let's look at some code.

//公共的   类   类名publicclass HelloJJAVA {    // 公共的 静态 无返回值 main方法 数组    publicstaticvoidmain(String[] str) {        new Person();    }}class Person {    {        System.out.println("我是构造方法");    }}

You want to know what he's running?

Why, the method does not have a name, it runs, this {} is the construction method?
If you substitute more than one construction method, you will find that he dropped Ouyong many times, this phenomenon, we can explain

To construct a code block:

    • The function is to initialize the object.
    • And it takes precedence over the construction method

And the difference between the construction method:

    • Constructing a code block is a unified initialization for all objects
    • The constructor is initialized to the corresponding object.

The constructor defines the initialization content (extraction) of different object commonalities.

OK, we continue to the next chapter, the concept of Java ideas need to thoroughly understand, all the blog slowly updated love Android can add group: 555974449

Java Tour (iv)-object oriented thinking, member/local variables, anonymous objects, encapsulation, private, construction methods, building blocks of code

Related Article

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.