Privatization of Java class properties

Source: Internet
Author: User

1. Create a students class

Properties of the Public class students{  //students class     private String  Name;    private int age;    private string gender ; Method of     //students Class     public students () {      //default Method      }  public students (String name,int age, String gender) {     //students class construction method        this.name = name ;   this.age = age ;    this.gender = gender ;     }    // The Get method of students gets the property value     public string getname () {       return this.name;     }    public int getage () {        &NBsp;return this.age;     }    public string  Getgender () {      return this.gender;     }  The    //students set method assigns a value to the property     public void setname (String  Name) {      this.name = name ;  }  public  void setage (int age) {    //Scoping and judging of age      if ( age>45 | |  AGE<15) {    this.age=18;   }else{    this.age  = age ;   }     }  public void  Setgender (String gender) {      this.gender = gender ;   } }

2. Create a Studentsdemo test class

public class Studentsdemo {public static void main (string[] args) {//Instantiating object Students st = new Students ();  St.name= "Xiao Ming";//st.age=12;//st.gender= "male";    System.out.println (st.name+ "\ n" +st.age+ "\ n" +st.gender+ "\ n");  St.setname ("Xiao Hu");  St.setage (14);  St.setgender ("male"); System.out.println (St.getname () + "\ n" +st.getage () + "\ n" +st.getgender () + "\ n"); }}

Output Result:
Xiao Hu
18
Man

This article is from the "Advanced Technology" blog, so be sure to keep this source http://vipnoon.blog.51cto.com/7589908/1792786

Privatization of Java class properties

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.