Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Constructor undefined?

Ok, I am working on an assignment for school, and I set up my main class and also another class called Transaction. In my main class I have:

Transaction t = new Transaction();

And Transaction is underlined: it says that the constructor undefined. WHY?!

The Transaction class looks like this:

public class Transaction {

private String customerNumber, fName, lName, custAddress, custCity;
private int custZip, custPhone;

/** Constructor*/
public Transaction(String a, String b, String c, String d, String e, int f, int g){
    this.customerNumber = a;
this.fName = b;
this.lName =c;
this.custAddress = d;
this.custCity = e;

}

It looks like it should just work, but it's just not. Even when I plug in a bunch of variables into where I make the new Transaction object in main, it still says undefined. Somebody please help!

like image 839
Jerry Avatar asked Sep 11 '10 05:09

Jerry


People also ask

Why is Java saying my constructor is undefined?

this compilation error is caused because the super constructor is undefined. in java, if a class does not define a constructor, compiler will insert a default one for the class, which is argument-less. if a constructor is defined, e.g. super(string s), compiler will not insert the default argument-less one.

How do you fix a undefined constructor?

To fix it, perform an undefined check on the variable before trying to access the constructor property. Using the optional chaining operator on a variable will return undefined and prevent the property access if the variable is nullish ( null or undefined ).

What happens if you don't define a constructor?

If we don't define a constructor in a class, then the compiler creates a constructor(with no arguments) for the class. And if we write a constructor with arguments or no arguments then the compiler does not create a default constructor.


2 Answers

There is no default constructor definition in your class.

When you provide the definition of at least one parameterized constructor the compiler no longer provides you the default constructor.

like image 105
Prasoon Saurav Avatar answered Oct 01 '22 02:10

Prasoon Saurav


This is because you haven't declared a constructor with no arguments.

When you have no constructor defined at all, there is a default constructor with no arguments defined automatically for you.

But now that you've declared a constructor with arguments, you now need to pass them or declare another constructor with no arguments.

like image 45
Tom Avatar answered Oct 01 '22 02:10

Tom