一、对象数组
类型为对象的数组,称为对象数组
package test;
public class Student {
private String name;
private double score;
public Student(String name, double score) {
this.name = name;
this.score = score;
}
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
package test;
public class TestStudent {
public static void main(String[] args) {
Student stu0 = new Student("张三1",68);
Student stu1 = new Student("张三2",28);
Student stu2 = new Student("张三3",100);
Student stu3 = new Student("张三4",98);
Student stu4 = new Student("张三5",46);
Student stu5 = new Student("张三6",33);
Student stu6 = new Student("张三7",27);
Student stu7 = new Student("张三8",18);
Student stu8 = new Student("张三9",9);
Student stu9 = new Student("张三10",0);
Student[] stus = {stu0,stu1,stu2,stu3,stu4,stu5,stu6,stu7,stu8,stu9};
double total = 0;
for(int i=0;i<stus.length;i++){
Student stu = stus[i];
System.out.println(stu.getName()+" "+stu.getScore());
total += stu.getScore();
// System.out.println(stus[i].getName());
}
double avg = total / stus.length;
System.out.println(avg);
}
}
张三1 68.0
张三2 28.0
张三3 100.0
张三4 98.0
张三5 46.0
张三6 33.0
张三7 27.0
张三8 18.0
张三9 9.0
张三10 0.0
42.7
二、继承
1、什么是继承?
使用extends关键字实现类的加载机制称之为继承,子类自动拥有了基类(也叫父类,superclass)的所有成员,即成员变量和成员方法。
2、注意
- Java只支持单继承,不支持多继承,即:一个子类只能有一个基类(父类),但是一个基类可以有多个子类;
- 子类对象包含父类对象;
- 静态方法是不可以继承的。
3、实例
package person;
public class Person {
public String name; //名字
public String occupation; //职位
public void eat(){
System.out.println(this.name+"能吃饭");
}
}
package person;
public class Coder extends Person{
public void coding(){
System.out.println(super.name+"能敲代码");
}
@Override
public void eat() {
System.out.println(this.name+"吃盒饭");
}
}
package person;
public class Leader extends Person{
public void watching(){
System.out.println(super.name+"监督程序员写代码");
}
@Override
public void eat() {
System.out.println(this.name+"吃满汉全席");
}
}
package person;
public class TestPerson {
public static void main(String[] args) {
Coder c = new Coder();
c.name = "张三";
c.eat();
c.coding();
Leader i = new Leader();
i.name = "李四";
i.eat();
i.watching();
}
}
张三吃盒饭
张三能敲代码
李四吃满汉全席
李四监督程序员写代码
三、super关键字
Super关键字,可以用来子类调用父类的成员用,它包括调用父类的public、protected修饰的变量方法。
1、注意
-
调用父类的方法:super.父类的方法;
-
同时super也可以调用父类的构造方法,但是父类中构造方法用private修饰时,不能有子类去继承;
-
子类可以没有构造方法,他会自动调用父类的构造方法;
-
在子类中可以调用父类的构造方法,super必须放在子类构造方法的首句。