7.类与对象

面向对象:oop object oriented proogramming

面向对象特征:封装继承多态
类与对象的关系:类是抽象的,对象是类的实例
类是由类得成员组成(成员变量,成员方法);
默认初始化,少不了。

类的定义

Public class className{}
对于基本数据类型中的布尔类型,getter方法用isMale
This写在方法里,谁调用谁就是this
构造方法,专门来创造对象的方法
注意事项 必须和类名大小写一样
3. 不要返回值类型
4. 构造方法不能返回值
5. 如果没有构造方法 系统会赠送一个构造方法
6. 一旦编写一个构造方法系统将不会赠送。

例子 一个学生类

package student.java;

public class Person {
//成员变量
	private int age;
	private String name;
	private String school;
	private String major;
//有参构造
	public Person(int age, String name, String school, String major) {
		super();
		this.age = age;
		this.name = name;
		this.school = school;
		this.major = major;
	}
//因为属性私有,只能本类访问,所以加入gettersetter方法方便其他的类调用
	public String getSchool() {
		return school;
	}

	public void setSchool(String school) {
		this.school = school;
	}

	public String getMajor() {
		return major;
	}

	public void setMajor(String major) {
		this.major = major;
	}
//构造方法重载
	public Person(int age, String name,String school) {
		this.name=name;
		this.age=age;
		this.school=school;
		
	}

	public Person(int age, String name) {
		
		this.age = age;
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		
		return age;
	}

	public void setAge(int age) {
		if(age>0&&age<130){
		this.age = age;
		}else{
			System.out.println("输入年龄有误");
		}
	}

}

类的实例化—创建对象

package student.java;

public class PersonTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		/*
		 * Person p1=new Person(18,"hcl");
		 * 
		 * System.out.println(p1.getAge()+p1.getName());
		 * System.out.println("================"); Person p2=new Person();
		 * p2.setAge(18); p2.setName("smz");
		 * System.out.println(p2.getAge()+p2.getName());
		 */
		Person p1 = new Person(18, "hcl");
		System.out.println("age:  "+p1.getAge()+"  name:  "+p1.getName());
		System.out.println("============================================");
		Person p2 = new Person(18, "hcl", "梵蒂冈");
		System.out.println("age:  "+p2.getAge()+"  name:  "+p2.getName()+"  school:  "+p2.getSchool());
		System.out.println("============================================");
		Person p3 = new Person(18, "hcl", "梵帝高", "计算机科学与技术(软件开发)");
		System.out.println("age:  "+p3.getAge()+"  name:  "+p3.getName()+"  school:  "+p3.getSchool()+"  major:  "+p3.getMajor());
		System.out.println("============================================");
		p3.setAge(21);
		System.out.println("age:  "+p3.getAge()+"  name:  "+p3.getName()+"  school:  "+p3.getSchool()+"  major:  "+p3.getMajor());
		
	}

}

上一篇:PAT甲级——A1080 Graduate Admission


下一篇:Entity Framework 导航属性(2)