Learn the package of Java tutorials

Source: Internet
Author: User

Learn to program the Java Tutorial package released, you are welcome to visit through the xuebiancheng8.com

The following is an analysis of the encapsulation in object-oriented, and what is encapsulation. First, segment code.

public class person{

String username;

int age;

}

Person p = new person ();

P.username= "Zhang San";

p.age=-10;

The above instantiation of a person object p, and then assignment, here we assign the age value to 10, here is obviously not correct, because the age can not be negative, then how to do it, here we will username,age these two properties to privatize, not let the outside can give him value. So the code becomes this way

public class person{

Private String username;

private int age;

Public String GetUserName () {

return username;

}

public void Setusername (String username) {

This.username = Username;

}

public int getage () {

return age;

}

public void Setage (int.) {

if (age<0) {

Age = 0;

}else{

This.age = age;

}

}

}

Person p = new person ();

P.setusername ("Zhangsan");

P.setage (-10);

So after the setter and getter method, the user if the assignment is negative, then his value is 0, which is the encapsulation, the property is privatized, and the setter and getter method is generated, in the future class if there are attributes, the general situation will be encapsulated.

Please visit xuebiancheng8.com for details.

The specific URL is

Http://xuebiancheng8.com/play/goodgoodstudy_92_daydayup.html


Learn the package of Java tutorials

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.