[Java]OOP的学生类

/*
学生类,这个类主要是要说明OOP的一很多要点
封装学生类中的属性,set和get方法,无参到两个参数的构造方法等
*/
class Student{
	private String name;
	private int age;
	public void setName(String name){
		this.name = name;
	}
	public void setAge(int age){
		this.age = age;
	}
	public String getName(){
		return this.name;
	}
	public int getAge(){
		return this.age;
	}
	
	public Student(){};//无参构造方法,省略这一行系统会自动默认加上.
	
	public Student(String n){	//定义有一个参数(String)的构造方法
		this.setName(n); 
	}
	
	public Student(int a){	//定义有一个参数(int)的构造方法
		this.setAge(a);
	}
	
	public Student(String n,int a){	//定义有两个参数的构造方法
		this.setName(n);	this.setAge(a);
	}
	
	public void print(){	//定义打印方法
		System.out.println("Name:"+ getName()+";年龄:"+ getAge());
	}
}
public class Demo{
	public static void main(String args[]){
		Student s1 = new Student(); //实际调用了默认的可以省略的无参构造方法
		s1.setName("张三");	s1.setAge(18);
		s1.print();
		
		Student s2 = new Student("李四");//调用一个参数(String)的构造方法
		s2.print();
		
		Student s3 = new Student(19);//调用一个参数(int)的构造方法
		s3.print();
		
		Student s4 = new Student("王五",20);//调用两个参数(int)的构造方法
		s4.print();		
		
		new Student("赵六",21).print();//采用匿名对象方法,这个对象打印完再见,以后不再使用.因为没有名字,以后你想用它也不能.
	}
}
/*
Name:张三;年龄:18
Name:李四;年龄:0	//未设置值的年龄为默认值0
Name:null;年龄:19	//未设置值的姓名为默认值null
Name:王五;年龄:20
Name:赵六;年龄:21
*/

发布了15 篇原创文章 · 获赞 1 · 访问量 4132

猜你喜欢

转载自blog.csdn.net/jsqdsq/article/details/78268293