继承和接口的区别
java继承是单继承,实现接口可以看做是对继承的一种补充。
实现接口可在不打破继承关系的前提下,对某个类功能扩展,非常灵活。
实例:
interface Fish
{
//该方法实现了....
public void swimming();
}
class Monkey
{
int name;
public void jump()
{
System. out.println( "猴子会跳");
}
}
class LittleMonkey extends Monkey implements Fish
{
@Override
public void swimming() {
// TODO Auto-generated method stub
}
}
实例:
public class Test1 {
public static void main (String args[])
{
CarShop carshop = new CarShop();
carshop.sellCar( new BMW());
carshop.sellCar( new QQ());
System. out.println( "总收入"+carshop.getMoney());
}
}
interface Car
{
//汽车名字
String getName();
//汽车价格
int getPrice();
}
//宝马
class BMW implements Car
{
public String getName()
{
return "BMW";
}
public int getPrice()
{
return 300000;
}
}
class QQ implements Car
{
public String getName()
{
return "QQ";
}
public int getPrice()
{
return 100000;
}
}
//汽车4S
class CarShop
{
private int money = 0;
public void sellCar(Car car)
{
System. out.println( "车型"+car.getName()+"单价" +car.getPrice());
money+=car.getPrice();
}
public int getMoney()
{
return money;
}
}
final final可以修饰变量或者方法;
final修饰的变量又叫常量,一般用xx-xx-xx命名
final修饰的变量在定义时,必须赋值。并且以后不能再赋值。
1 当不希望父类的某个方法被子类覆盖时。可以用final关键字修饰。
2 当不希望类的某个变量被修改,可以用final修饰。
3 当不希望类被继承时。可以在类前面加final。
final class Kkk
{
}
class Aaa
{
//用final修饰,表面该方法不可以被修改。不可能被覆盖。
final public void sendMes()
{
System.out.println("发送消息");
}
}
来源:oschina
链接:https://my.oschina.net/u/4312789/blog/4317672