为什么构造函数上的继承不起作用?我怎样才能使它有效? [英] Why does inherits on constructor is not working ? how can I make it works ?

查看:63
本文介绍了为什么构造函数上的继承不起作用?我怎样才能使它有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是java的初学者,我尝试使用构造函数进行继承,但似乎没有工作。



我有什么试过:



I'm a beginner in java and I try to work on inheritance using constructor, but it seems not to be working.

What I have tried:

import java.io.*;
public class Person {
    String name;
    String address;
    String tel_no;
    String answer;
  
  public Person(String name, String address, String tel_no, String answer) {
    this.name = name;
    this.address = address;
    this.tel_no = tel_no;
    this.answer = answer;
  }
}
class Bar {
    public static void main(String[] args) throws IOException {
    BufferedReader k=new BufferedReader(new InputStreamReader
            (System.in));
  String answer = "no";
do{
    System.out.print("Please enter name: ");
    String name=k.readLine( );  // local variable
    System.out.print("Please enter address: ");
    String address=k.readLine( );
    System.out.print("Please enter phone number: " ); // to handle the end of line characters
    String tel_no =k.readLine( );
    System.out.print("Is your information Correct? ");
    answer=k.readLine( );
    // use local variables in constructor call
    Person person = new Person(name, address, tel_no, answer);    
} while(answer.equals("no"));
}

//subclass
import java.io.*;
public class Customer extends Person{
    String ID;
  
  public Customer(String ID) {
    this.ID = ID;
  }
}
class Geren {
    public static void main(String[] args) throws IOException {
    BufferedReader k=new BufferedReader(new InputStreamReader
            (System.in));
  String answer = "no";
    do{
    System.out.print("Please enter your ID number: ");
    String ID=k.readLine( );
    Customer cust = new Customer(ID);    
    } while(answer.equals("no"));
  }
}

推荐答案

类有一个构造函数,需要四个参数 - name address tel_no 回答



客户 class扩展 Person 类。它有一个构造函数,它接受一个参数 - ID - 并且不调用基础构造函数。



你总是要调用超类的构造函数。在这种情况下,您需要将缺少的参数添加到 Customer 构造函数。

The Person class has a single constructor which expects four parameters - name, address, tel_no, and answer.

The Customer class extends the Person class. It has a single constructor which accepts a single parameter - ID - and does not call the base constructor.

You always have to call the constructor of the super class. In this case, you will need to add the missing argument to the Customer constructor.
public class Customer extends Person{
    String ID;
    
    public Customer(String ID, String name, String address, String tel_no, String answer) {
        super(name, address, tel_no, answer);
        this.ID = ID;
    }
}



使用关键字超级(Java™教程>学习Java语言>接口和继承) [ ^ ]


这篇关于为什么构造函数上的继承不起作用?我怎样才能使它有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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