类与对象
1.类与对象
类是一个模板:抽象对象是一个具体的实例
2.方法
定义调用
3.对象的引用
引用类型:基本类型(8)
对象是通过引用来操作的:栈-->堆
4.属性:字段field 成员变量
默认初始化
数字: 0 0.0
char: u000
boolean: false
引用: null
修饰符 属性类型 属性名 = 属性值!
5.对象的创建和使用
--必须使用new关键字创造对象,构造器 Person woziji=new Person();
--对象的属性 woziji.name
--对象的方法 woziji.sleep()
6.类
静态的属性
动态的行为
例题:
定义一个Student类,其中有成员变量,学号,姓名,性别,是否为班干部,以及语文数学英语的分数,求成绩的方法。
定义一个主类,主方法中通过学生类创造对象,通过键盘输入对象属性值,然后输出学生的属性值,调用方法输出该学生的总成绩与平均成绩。
实验代码
public class Student{
String numbers;
String name;
String sex;
boolean sector;
double[] score=new double[3];
public static void score(double score[]){
double sum=0;
int i;
for(i=0;i<3;i++){
sum=sum+score[i];
}
System.out.println("总成绩为:"+sum+"平均成绩为:"+(sum/i));
}
}
public static void main(String[] args){
Student student=new Student();
double[] arr=new double[3];
Scanner scanner=new Scanner(System.in);
System.out.println("请输入学生学号:");
student.numbers=scanner.next();
System.out.println("请输入学生姓名:");
student.name=scanner.next();
System.out.println("请输入学生性别:");
student.sex=scanner.next();
System.out.println("学生是否为班干部:");
student.sector=scanner.nextBoolean();
System.out.println("请输入学生成绩:");
for(int i=0;i<3;i++){
student.score[i]=scanner.nextDouble();
}
System.out.print("学生:"+student.name);
System.out.print("学号为"+student.numbers);
System.out.print("性别"+student.sex);
if(student.sector==true){
System.out.println("是班干部");
}else{
System.out.println("不是班干部");
}
Student.score(student.score);
scanner.close();
}

浙公网安备 33010602011771号