1. 类与对象:
2. 成员方法的修饰:从语义上理解,类是对象的模板,对象是类的实例,从语法上理解,类是一种数据类型,对象是这种类型的变量。在类的内部,方法可以直接访问该类的私有变量,但对于外部的类,则不可。注意类中的字段默认为private。
public,private,protected(权限修饰),static(类方法),final(修饰的方法不能被覆盖和重载)。
3. 封装
4. 类的设计规则:
(1)概念:
①.将属性私有化,提供公有方法访问私有属性
②.通过公有方法访问私有属性,通过setter和getter方法访问
(2)封装的实现:
①.修改属性的可见性来限制对属性的访问
②.为每个属性创建一对赋值(setter)方法和取值(getter)方法
③.在setter和getter方法中,加入对属性的存取限制
(3)技巧:快速封装类的字段:源文件中点击右键,选择"source",再选择"Generate Getters and setters..."。
①.取有意义的名字
②.尽量将数据设计为私有属性
③.尽量对变量进行初始化
④.类的功能尽量单一
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 + "]";
}
}
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