类与对象
类的概念
类在现实生活中指具有相似属性、特征、行为方式等的一类事物的集合。对应在代码中则是具有相同属性、特征行为方式等的一类对象的固定格式进行定义的模板。
类的组成
程序中类的是由两个部分组成:
1.属性
定义:是由对象的特征进行定义的,可以用一个数据/变量表达;
具体格式:访问修饰符 属性类型 属性变量名
具体语法:类名 对象名 = new 类名();
2.方法
定义:是由对象的行为进行定义,即需要用一个或多个代码块进行描述。
具体格式:访问修饰符 返回值类型 方法名 (参数类型 参数变量名){};
类创建的对象
格式:类名 对象变量名 = new 类名 ();
可以通过对象变量名调用这个对象的属性和方法,使用方法为:对象变量名.属性名/对象变量名.方法名();
编写程序的步骤
1、找到类中对象的特征和行为:
例如本场景应用于研究生录取工作,初试成绩由英语、政治、专业课1、专业课2组成,满分为500,占总成绩的70%,复试成绩满分100,占最后总成绩的30%,成绩高者被录取。
学生成绩 特征:英语分数、政治分数、专业课1分数、专业课2分数、复试分数
行为:总分,是否被录取。
2、根据对象的特征和行为去定义类(属性和方法)
在此场景中,英语分数、政治分数、专业课1分数、专业课2分数、复试分数都为int类型,总分为double型。
3.定义程序的入口主函数,在主函数中实例化对象和调用方法属性。
public class Students {
String name;
int English ;
int Politics ;
int Class1 ;
int Class2 ;
int Interview ;
int Score1;
Double Score;
public void Score(){
Score1 = English + Politics + Class1 + Class2 ;
Score = Score1 *0.2 * 0.7 + Interview * 0.3 ;
System.out.println(name+"初试总分为"+Score1+"总成绩为"+Score) ;
}
}
public class EnrollManger {
public static void main(String[] args) {
Students stu1 = new Students();
stu1.name="学生1";
stu1.Politics = 70 ;
stu1.English = 75;
stu1.Class1 = 120;
stu1.Class2 = 130;
stu1.Interview = 90;
System.out.println("姓名"+stu1.name);
System.out.println("英语分数"+stu1.English);
System.out.println("政治分数"+stu1.Politics);
System.out.println("专业课1分数"+stu1.Class1);
System.out.println("专业课2分数"+stu1.Class2);
System.out.println("面试分数"+stu1.Interview);
stu1.Score();
Students stu2 = new Students();
stu2.name="学生2";
stu2.Politics = 74 ;
stu2.English = 79;
stu2.Class1 = 116;
stu2.Class2 = 121;
stu2.Interview = 88;
System.out.println("姓名"+stu2.name);
System.out.println("英语分数"+stu2.English);
System.out.println("政治分数"+stu2.Politics);
System.out.println("专业课1分数"+stu2.Class1);
System.out.println("专业课2分数"+stu2.Class2);
System.out.println("面试分数"+stu2.Interview);
stu2.Score();
if (stu2.Score > stu1.Score){
System.out.println("学生2被录取");
}else{
System.out.println("学生1被录取");
}
}