"Java Basics" class package

Class packaging refers to the definition of a class, the class will be privatized in the property, that is decorated with a private key, private property can only be accessed in its class.

package one;                   //路径包是one

class Student{                 //Student类
	private String name;                    //将name属性私有化
	private int age;                        //将age属性私有化
	                                //下面是公有的getXxx()和setXxx()的方法
	public String getName(){       
		return name;
	}
	public void setName(String stuName){
		name=stuName;                         //对name属性赋值
	}
	public int getAge(){
		return age;
	}
		public void setAge(int stuAge){
		                                  //下面是对传入的参数进行检查
			if(stuAge<=0){            //if...else语句
				System.out.println("年龄不合法....");
			}else{
				age=stuAge;              //对age属性赋值
			}
		}
	public void intruduce(){
	//方法中打印属性name和age的值
		System.out.println("大家好,我叫"+name+",我今年"+age+"岁!");
	}
}

class day01{
	public static void main (String[] args){
		Student stu=new Student();     //类名 对象名称=new 类名();
		stu.setAge(-30);
		stu.setName("李芳");
		stu.intruduce();         //调用对象的方法
	}
	
}

1, Student class, use the keyword private property name and age declared private, foreign public offers several ways to
value 2, getName () method used to obtain the name attribute, setName () method is used to set the name attribute value, empathy getAge () and the setAge () method is used to get and set the value of the age attribute.
3, is created in main () method student object and call the setAge () method passing a negative number -30, a check of the value of the parameter StuAge serAge () method, since the current value is less than 0 is passed,
therefore Print "age is not legal" information, age attribute is not assigned, the default initial value is still 0
 

Published 32 original articles · won praise 11 · views 6195

Guess you like

Origin blog.csdn.net/Cai1010110/article/details/102829302