Java继承示例 [英] Java Inheritance Example

查看:161
本文介绍了Java继承示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是继承的示例

class Parent {
    Parent(int a, int b) {
        int c = a + b;
        System.out.println("Sum=" + c);
    }
    void display() {
        System.out.println("Return Statement");
    }
}
class Child extends Parent {
    Child(int a, int b) {
        int c = a - b;
        System.out.println("Difference=" + c);
    }
}
public class InheritanceExample {
    public static void main(String args[]) {
        Child c = new Child(2, 1);
        c.display();
    }
}

我没有时遇到以下错误非参数化构造函数parent()

I get the below error when I don't have the non-parametrized constructor parent()

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Implicit super constructor Parent() is undefined. Must explicitly invoke another constructor

    at Child.<init>(InheritanceExample.java:14)
    at InheritanceExample.main(InheritanceExample.java:22)

您能否解释一下基类中构造函数没有参数的目的是什么。

Can you please explain me what is the purpose of the constructor without parameters in base class.

推荐答案

class child extends parent
{
    child(int a,int b)
    {
        int c=a-b;
        System.out.println("Difference="+c);
    }
}

子类构造函数必须做的第一件事就是调用父类构造函数。
如果你没有明确地这样做(例如 super(a,b)),则暗示默认构造函数的调用( super ())。

The first thing the child class constructor must do is call the parent class constructor. If you do not do this explicitly (e.g. super(a,b)), a call to the default constructor is implied (super()).

为此,必须使用此默认构造函数(不带任何参数)。

For this to work, you must have this default constructor (without any parameters).

如果您没有声明任何构造函数,则会获得默认构造函数。如果您声明至少一个构造函数,则不会自动获取默认构造函数,但您可以再次添加它。

If you do not declare any constructors, you get the default constructor. If you declare at least one constructor, you do not get the default constructor automatically, but you can add it again.

您收到的错误消息是抱怨隐含的调用 super()不起作用,因为父类中没有这样的构造函数。

The error message you are getting is complaining about the implied call to super() not working, because there is no such constructor in the parent class.

两种方法修复它:


  1. 在子构造函数的第一行添加默认构造函数

  2. ,调用非默认父构造函数( super(a,b)

  1. add a default constructor
  2. in the first line of the child constructor, call a non-default parent constructor (super(a,b))

另外,请不要使用全小写的类名。

Also, please don't use all-lowercase class names.

这篇关于Java继承示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆