Java学习笔记(四)类与对象

1. 类与对象:

从语义上理解,类是对象的模板,对象是类的实例,从语法上理解,类是一种数据类型,对象是这种类型的变量。在类的内部,方法可以直接访问该类的私有变量,但对于外部的类,则不可。注意类中的字段默认为private。

2. 成员方法的修饰:

public,private,protected(权限修饰),static(类方法),final(修饰的方法不能被覆盖和重载)。

3. 封装

(1)概念:

①.将属性私有化,提供公有方法访问私有属性

②.通过公有方法访问私有属性,通过setter和getter方法访问

(2)封装的实现:

①.修改属性的可见性来限制对属性的访问

②.为每个属性创建一对赋值(setter)方法和取值(getter)方法

③.在setter和getter方法中,加入对属性的存取限制 

(3)技巧:快速封装类的字段:源文件中点击右键,选择"source",再选择"Generate Getters and setters..."。

4. 类的设计规则:

①.取有意义的名字

②.尽量将数据设计为私有属性

③.尽量对变量进行初始化

④.类的功能尽量单一

5. 构造函数满足的规则:

①.方法名与类名相同

②.没有返回类型,注意也不能为void

6. 使用new关键字调用构造方法,构造方法非常适于对属性的初始化

①.自己编写的有参构造函数会替换默认的潜在构造函数。

②.构造方法不能手工调用,会在创建类的对象时被系统自动调用。

③.一个类可以没有构造方法(隐式的无参构造方法),也可以有多个构造方法,他们之间构成重载关系。

④.构造方法不能被继承。


注意事项:

①自动初始化只适用于成员变量,方法体中的局部变量不能被自动初始化,必须赋值后才能使用

②在java中,如果一个类没有明显的表明哪一个类是它的父类,Object将会被默认为它的父类。


程序说明:

首先,构造一个Student类:

public class Student {
	public String name;
	public char sex;
	public String birthday;
	private int compuScore,mathScore;
	
	//构造函数初始化成员变量
	public Student(String name, char sex, String birthday) {
		super();
		this.name = name;
		this.sex = sex;
		this.birthday = birthday;
	}

	public int getCompuScore() {
		return compuScore;
	}

	public void setCompuScore(int compuScore) {
		this.compuScore = compuScore;
	}

	public int getMathScore() {
		return mathScore;
	}

	public void setMathScore(int mathScore) {
		this.mathScore = mathScore;
	}
	
	//求取学生成绩的平均分
	public double getAverScore(){
		return (compuScore+mathScore)/2.0;
	}
	
	//获取最高成绩
	public int getMaxScore(){
		int max;
		if(compuScore>mathScore)
			max = compuScore;
		else
			max = mathScore;
		return max;
	}

	@Override
	public String toString() {
		return "Student [name=" + name + ", sex=" + sex + ", birthday="
				+ birthday + ", compuScore=" + compuScore + ", mathScore="
				+ mathScore + "]";
	}
	
	
}


其次,编写测试类testStudent:

public class testStudent {
	public static void main(String[] args) {
		Student stu = new Student("Daniel",'M',"1999.1.2");
		System.out.println(stu.toString());
		stu.birthday = "1989.3.11";
		System.out.println(stu.toString());
		stu.setCompuScore(90);
		stu.setMathScore(85);
		System.out.println("计算机成绩:"+stu.getCompuScore());
		System.out.println("数学成绩:"+stu.getMathScore());
		System.out.println("平均成绩:"+stu.getAverScore());
		System.out.println("最高成绩:"+stu.getMaxScore());
	}
}

测试的结果为:

Student [name=Daniel, sex=M, birthday=1999.1.2, compuScore=0, mathScore=0]
Student [name=Daniel, sex=M, birthday=1989.3.11, compuScore=0, mathScore=0]
计算机成绩:90
数学成绩:85
平均成绩:87.5
最高成绩:90




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mengrennwpu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值