在java语法中继承_继承及其在Java中的实现

Java继承Java中的继承是一种允许类继承其他类的功能的方法。

也称为IS-A关系。

通过使用extends关键字,我们可以在java中实现继承。

继承的优点是代码的可重用性。

与继承相关的重要术语:父类:

也称为超类或基类,父类的定义是其属性(或特征)被继承的类。

子类:

也称为子类或派生类,子类的定义是继承其他类的属性(或功能)的类。

如何在Java中实现继承?

我们借助extends关键字实现继承。

语法:class Parent {

public void method1() {

//字段和声明

}

}

class Child extends Parent {

public void method2() {

//字段和声明

}

}

示例

在下面的继承示例中,Parent类是父类,Child类是扩展Parent类的子类。/*Java program to demonstrate the

concept of inheritance */

//家长班

class Parent {

//Parent类有一种方法

// displayParentMessage()打印父类消息的方法

public void displayParentMessage() {

System.out.println("Hello, we are in parent class method");

}

}

//子类或派生类

class Child extends Parent {

//Child子类添加了另一种方法

// displayChildMessage()打印父类消息的方法

public void displayChildMessage() {

System.out.println("Hello, we are in child class method");

}

}

//我们将在该类的主类中创建

//父子类的对象

class Main {

public static void main(String[] args) {

//创建父类对象

Parent p = new Parent();

//通过父类对象调用父类方法

p.displayParentMessage();

//创建Child类对象

Child c = new Child();

//通过子类对象调用子类方法

c.displayChildMessage();

//通过子类对象调用父类方法

c.displayParentMessage();

}

}

输出结果D:\Programs>javac Main.java

D:\Programs>java Main

Hello, we are in parent class method

Hello, we are in child class method

Hello, we are in parent class method

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值