尝试在main中调用子类的构造函数

时间:2019-05-20 19:40:19

标签: java windows eclipse

我正在用Java编写程序,并且遇到了这个问题。

我已经做了一个抽象的超类Customer和一个子类RegisteredCustomer,当然也做了主类。我找不到在主体中使用RegisteredCustomer的构造函数的方法。

即使我在The method RegisteredCustomer(String, long, String, String) is undefined for the type RegisteredCustomer中使用这些参数创建了确切的构造函数,也出现了消息RegisteredCustomer

我尝试了RegisteredCustomer.RegisteredCustomer(fn , tel , adr , em);Customer.RegisteredCustomer.RegisteredCustomer(fn , tel , adr , em);

registeredCUSTOMER

public class RegisteredCustomer extends Customer {

    private static int count = 0;

    private int id;
    private String email;
    private String  password;

    public RegisteredCustomer(String fullName, long telephone, String adress, String email) {
        super(fullName, telephone, adress);
        this.id = ++ count;
        this.email = email;
        Customer.getCustomers().add(Customer.getCustomers().size() , this);
    }

主要

RegisteredCustomer.RegisteredCustomer(fn , tel , adr , em);

3 个答案:

答案 0 :(得分:3)

使用RegisteredCustomer.RegisteredCustomer(fn , tel , adr , em);试图调用类RegisteredCustomer的静态方法RegisteredCustomer,该方法不存在,因此它告诉您该方法未定义。

下面的代码是您尝试调用的方法的示例。

public class RegisteredCustomer {

    ...

    public static void RegisteredCustomer(String fullName, long telephone,
            String adress, String email) {
        ...
    }
}

创建RegisteredCustomer实例的正确方法是调用:

new RegisteredCustomer(fn , tel , adr , em);

答案 1 :(得分:1)

我不确定,但是尝试创建一个演示类并在其中编写:

RegisteredCustomer rc = new RegisteredCustomer(fn, tel, adr, em);

然后您可以在那里更改对象。

答案 2 :(得分:0)

在Java中初始化对象的方式似乎存在语法错误。以下是一种编写方法,

public class TestClass {
    public static void main(String[] args) {
        RgisteredCustomer rc = new RgisteredCustomer("John D", 9175556671L, "NYC", "john.d@gmail.com"); //This is how the base and super class constructors are called
        System.out.println(rc);
    }
}

class Customer {
    private String fullName;
    long telephone;
    String address;
    Customer(String fullName, long telephone, String address) {
        this.fullName = fullName;
        this.telephone = telephone;
        this.address = address;
    }
    public String toString() {
        return fullName + " " + telephone + " " + address;
    }
}

class RgisteredCustomer extends Customer {
    private static int count = 0;
    private int id;
    private String email;
    private String  password;

    public RgisteredCustomer(String fullName, long telephone, String adress, String email) {
        super(fullName, telephone, adress);
        this.id = ++ count;
        this.email = email;
        //Customer.getCustomers().add(Customer.getCustomers().size() , this);
    }
    public String toString() {
        return super.toString() + " " + email + " " + password;
    }
}

在Java中,此RegisteredCustomer.RegisteredCustomer(fn,tel,adr,em)/Customer.RegisteredCustomer.RegisteredCustomer(fn,tel,adr,em)将意味着调用静态方法。