在java中,继承是oop(面向对象编程)的重要支柱,它是java中的一种机制,通过该机制,一个类可以继承另一个类的功能(字段或者方法)。在java中,继承意味着基于现有的类创建新类。从另一个类继承的类可以重用该类的方法方法和字段。此外,您还可以向当前类添加新字段和方法。
为什么需要java继承?
(1)代码的可重用性:父类中的编写的代码对于所有子类都是通用的。子类可以直接是由使用父类的代码。
(2)方法重写:方法重写只能通过继承来实现。它是java中实现多态的方式之一。
(3)抽象:抽象的概念是通过继承来实现的,我们不必提供所有的细节。抽象仅仅向用户展示功能。
Java继承中使用的重要术语
(1)类是一组具有共同特征或者行为和公有属性的对象。类不是现实世界的实体。它只是创建对象的模板,蓝图或者原型。
(2)父类:其功能被继承的类称为超类(或者基类)。
(3)子类:继承其他类的类称为子类(或者派生类,扩展类或者子类)。除了父类的字段和方法外,子类还可以添加自己的方法和字段。
(4)可用性:继承支持可重用性的概念,当我们想要创建一个新类并且已经有一个类包含我们想要的一些代码时,我们可以从现有类派生新类,这样做,我们就重用了现有类的字段和方法。
Java中如何使用继承?
在java中,extends关键字用于继承。使用extends关键字表明您是从现有类派生的。换句话说,“extends”是指新增加的功能。
例如:
class 子类 extends 父类
{
方法和字段;
}
JAVA中继承的示例
例如:在下面的示例中,类BIcycle是基类,类MountainBike是扩展Bicycle的派生类,类Test是运行程序的驱动程序类。
// Java program to illustrate the
// concept of inheritance
// base class
class Bicycle {
// the Bicycle class has two fields
public int gear;
public int speed;
// the Bicycle class has one constructor
public Bicycle(int gear, int speed)
{
this.gear = gear;
this.speed = speed;
}
// the Bicycle class has three methods
public void applyBrake(int decrement)
{
speed -= decrement;
}
public void speedUp(int increment)
{
speed += increment;
}
// toString() method to print info of Bicycle
public String toString()
{
return ("No of gears are " + gear + "\n"
+ "speed of bicycle is " + speed);
}
}
// derived class
class MountainBike extends Bicycle {
// the MountainBike subclass adds one more field
public int seatHeight;
// the MountainBike subclass has one constructor
public MountainBike(int gear, int speed,
int startHeight)
{
// invoking base-class(Bicycle) constructor
super(gear, speed);
seatHeight = startHeight;
}
// the MountainBike subclass adds one more method
public void setHeight(int newValue)
{
seatHeight = newValue;
}
// overriding toString() method
// of Bicycle to print more info
@Override public String toString()
{
return (super.toString() + "\nseat height is "
+ seatHeight);
}
}
// driver class
public class Test {
public static void main(String args[])
{
MountainBike mb = new MountainBike(3, 100, 25);
System.out.println(mb.toString());
}
}
输出:
No of gears are 3//(档位数为3)
speed of bicycle is