The Java Learning Package

Source: Internet
Author: User
Tags modifier

Package Hello2;
public class Person {
String name;
int age;
public void Book () {
System.out.println ("reading");
}
public void TV () {
System.out.println ("watch TV");
}
}

  1. Encapsulation is used in order to limit the use of class attributes, such as the above age is not very large, which requires encapsulation to implement

  2. Packaging

    /span>

    package Hello2;
    public class Person {
     private String name;// using the private modifier is a property privatization using the private modifier to privatize properties ,  private int age; After privatization, it can only be used inside the class, not externally,
      Private int age; //Use the method to assign a value to the Name property, You can use external (. setName), and then restrict the use of
      public void SetName (String n) {
       name=n;   in the method;
       }
     public void setage (int m) {// for external use, provide a public Getter/setter method for the property (the operation of the property is only" save "(set method) and" Fetch "(Get method), this method is to use" save "
       if (m>0&&m<120)//

    then add some control code
    Age=m;
    }

    Public String GetName () {
        return name;
      }
       public int getage () {//This method is "fetch", to have a return value
        return age;
      }
        public void Book () {
        System.out.println ("reading" );
      }
       public void TV () {
        System.out.println ("watch TV");
      }
}
Package Hello2;
public class Testperson {
public static void Main (string[] arges) {
Person P=new person ();
P.name= "AAA"; cannot be used after privatization
P.setname ("AAA");
P.setage (34);
String N=p.getname ();
int A=p.getage ();
System.out.println (n+ "\ t" +a);
}
}

Running Result: AAA 0

The Java Learning Package

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.