The little white said that he had not understood the class and the object yet, and I threw this article to him in a rage

2nd Brother, I was the one who said that you did n’t understand "Teacher to Learn Spring" last time. I did n’t expect you to write an entry-level basic knowledge of Java . I really understood it this time. . Please forgive my last abruptness. My second brother can really take care of our little Bai's learning progress. It is really a conscience.

The above is the information that reader KEL specially sent me after the last basic knowledge article was published. To be honest, I was very moved after reading it, and my conscience was not let down. So, I happily decided to write an entry-level article every two weeks for Xiaobai to see.

Classes and objects are the two most basic concepts in Java, which can be said to support the sky of object-oriented programming (OOP). Objects can be any objects that can be seen in reality (a maverick pig), or any virtual objects that can be imagined (Sun Wukong, which can change seventy-two), Java defines these objects through classes What are the states (defined by fields or member variables, such as whether the color of the pig is a solid color or a color), and what behavior (defined by methods, such as the pig will eat and sleep).

Come, let me define a simple class for you to see.

public class Pig {
    private String color;

    public void eat() {
        System.out.println("吃");
    }
}

By default, every Java class has an empty constructor. Although it is the default in the source code, it can be seen by decompiling the bytecode.

public class Pig {
    private String color;

    public Pig() {
    }

    public void eat() {
        System.out.println("吃");
    }
}

That's right, it's the extra one public Pig() {}, the parameters are empty, and the method body is empty. We can use this construction method to create an object through the new keyword, the code is as follows:

 Pig pig = new Pig();

Of course, we can also actively add construction methods with parameters.

public class Pig {
    private String color;

    public Pig(String color) {
        this.color = color;
    }

    public void eat() {
        System.out.println("吃");
    }
}

At this time, when you look at the decompiled bytecode, you will find that the default parameterless construction method disappears-exactly the same as the source code.

public class Pig {
    private String color;

    public Pig(String color) {
        this.color = color;
    }

    public void eat() {
        System.out.println("吃");
    }
}

This means that by not new Pig()create an object - the compiler will remind you of the additional parameter.

For example, if you modify the code to new Pig("纯白色")add a parameterless construction method.

public class Pig {
    private String color;

    public Pig(String color) {
        this.color = color;
    }

    public Pig() {
    }

    public void eat() {
        System.out.println("吃");
    }
}

The default state of the object created using the parameterless construction method is null (color string is a reference type). If it is a basic type, the default value is the default value of the corresponding basic type. For example, int is 0. See the following figure for more details .

Next, let's create multiple Pig objects with different colors.

public class PigTest {
    public static void main(String[] args) {
        Pig pigNoColor = new Pig();
        Pig pigWhite = new Pig("纯白色");
        Pig pigBlack = new Pig("纯黑色");
    }
}

You see, we have created three Pig objects of different suits, all from a class, so we can see the importance of the class. It only needs to be defined once and can be used multiple times.

What if I want to change the state of the object? What should I do? There is currently no way, because there is no way to change the state, directly modify the color will not work, because its access right modifier is private.

The best way is to add getter / setter methods to the Pig class, like this:

public String getColor() {
    return color;
}

public void setColor(String color) {
    this.color = color;
}

By setColor()modifying the method by getColor()acquiring state method, their rights modifiers are public.

Pig pigNoColor = new Pig();
pigNoColor.setColor("花色");
System.out.println(pigNoColor.getColor()); // 花色

Why is it designed like this? You can directly change the access permission modifier of the color field to be public, isn't it the same effect as getter / setter?

Because in some cases, certain fields are not allowed to be modified at will, it is only initialized once when the object is created, such as the age of the pig, it can only grow one year a year (for example), there is no moonlight box to let it Change back.

private int age;

public int getAge() {
    return age;
}

public void increaseAge() {
    this.age++;
}

You see, age is no setter method can be invoked only once a year a increaseAge()method and getter methods. If you change the access modifier of age to public, age is completely out of control, and you can reset it to 0 or a negative number at will.

Access permission modifiers are very important for Java. There are currently four types: public, private, protected, and default (default).

A class can only use publicor defaultmodification, public-modified class has seen you before, I now define a default permission modifier you like to admire.

class Dog {
}

Haha, actually there is nothing to appreciate. The default means that this class can be accessed by other classes under the same package; and public means that this class can be accessed by classes under all packages.

If it is necessary to modify the class through private and protected, the compiler will be angry, it does not agree.

private can be used to decorate the constructors, fields, and methods of a class and can only be accessed by the current class. protected can also be used to modify the constructors, fields, and methods of a class, but its scope of permissions is wider and can be accessed by classes in the same package, or subclasses of the current class.

You can compare the difference between the four permission modifiers with the following picture:

  • No matter what kind of permission modifiers are in the same class, they can be accessed;
  • Under the same package, private decorated cannot be accessed;
  • Subclasses can access public and protected decoration;
  • The public modifier faces the world, haha, can be accessed from all places.

Well, my dear reader friends, this article intends to stop abruptly, what is not satisfactory, despite the message, I promise to give you the opportunity to go to the wall.

Thanks for reading

I learned Java when I was in junior college, but due to poor foundation and low education, I suffered a lot from my work. There is no way but to make up for it the day after tomorrow. The output is forced to input, so I started my own counterattack, constantly learning the core knowledge of Java, and writing all my experiences into articles, which were published on the blog platform. Unexpectedly, this persistent effort has achieved A better self.

If you are unwilling to be mediocre and do not want to be restricted by your academic qualifications, please join me in Daguai to advance!

I not only share interesting technology, but also share the useful life of the program, these will help you from a "cock silk" programmer to an advanced programmer.

I am looking forward to communicating with you, send me our WeChat account, qing_geee. If you have any questions, please feel free to communicate with me. In addition, I have formed some high-quality technical exchange groups. If you are interested, I can invite you Join.

All my articles will be posted on the "Silent King 2" public account and CSDN blog for the first time. If you happen to like my article, please search for " Silent King 2 " on WeChat .

Replying to the keyword "interview", you can get a valuable interview strategy for free, organized by the US group boss .

In addition to replying to "concurrency", you can also get a practical guide to Java concurrent programming organized by Ali Daniel, only for the first time you follow!

发布了690 篇原创文章 · 获赞 1万+ · 访问量 438万+

Guess you like

Origin blog.csdn.net/qing_gee/article/details/105581742