世界地球日,奏响低碳生活进行曲,以蓝天为乐谱,以绿树为音符,以碧水为琴弦弹奏出环保最强音,为地球母亲祈祷平安吃五谷杂粮,穿天然布衣,住节能住宅,行无车之旅,用厉行节俭。让我们怀着敬畏感恩之心,向地球母亲贺寿。

前言
在前面两周,我们分别学习了抽象类和接口,在上一周的学习中,不知道大家有没有注意到这样一句话“但当一个抽象类除了抽象方法外什么都没有的时候,用接口则更为合适”,即从这句话中,我们可以看出,其实接口也是一种特殊的抽象类。那么本周我们就来看看两者又有哪些联系与区别。
一、抽象类
在 Java 中,被关键字 abstract 修饰的类称为抽象类;被 abstract 修饰的方法称为抽象方法,抽象方法只有方法声明没有方法体。
抽象类有以下几个特点:
二、接口
接口可以看成是一种特殊的类,只能用 interface 关键字修饰。
Java 中的接口具有以下几个特点:
三、抽象类和接口的联系与区别
联系:
接口和抽象类很像,它们都具有如下特征:
区别:
四、接口和抽象类在用法上的区别
除了上述提到的区别之外,接口和抽象类在用法上也存在差别,如下表所示:

五、抽象类和接口的应用场景
抽象类的应用场景:
接口的应用场景:
小编有话说
小编最近有点忙,就先奉上上周习题的参考答案吧。大家加油哟!

考虑到图有点小,就把源码附上吧~
1.Student抽象类
package code.tisheng7;
public abstract class Student {
public int stuID;
public String name;
public float score;
public double weight;
public Student(int stuID, String name,float score) {//三个参数的构造方法
this.stuID = stuID;
this.name = name;
this.score = score;
}
public Student(int stuID, String name,float score,double weight) {//四个参数的构造方法
this.stuID = stuID;
this.name = name;
this.score = score;
this.weight = weight;
}
public abstract double getscore(); // 定义抽象方法,计算分数
}2.Pupil类
package code.tisheng7;
public class Pupil extends Student {
public Pupil(int stuID, String name,float score) {
super(stuID,name,score);
}
public String getname(){
return ("学号:"+stuID+","+name);
}
// 重写父类中的抽象方法,获得成绩
@Override
public double getscore() {
return score;
}
}3.Undergraduate类
package code.tisheng7;
public class Undergraduate extends Student {
public Undergraduate(int stuID, String name,float score,double weight) {
super(stuID,name,score,weight);
}
public String getname(){
return ("学号:"+stuID+","+name);
}
// 重写父类中的抽象方法,实现大学生的权重成绩
@Override
public double getscore() {
return score*weight;
}
}4.Test_student类
package code.tisheng7;
public class Test_student {
public static void main(String[] args) {
Pupil pupil = new Pupil(123, "李雷居士",89); // 创建pupil对象
System.out.println(pupil.getname()+"的成绩为:"+pupil.getscore());
// 创建圆Undergraduate对象
Undergraduate undergraduate = new Undergraduate( 456,"韩梅梅居士",98,0.6);
System.out.println(undergraduate.getname()+"加权成绩为:"+undergraduate.getscore());
}
}编辑:玥怡居士|审核:世外居士