-1

So I'm quite new to Java and this is the first time I'm working with objects. Could you help me out with why this piece of code doesn't work?

public class Object
{
    String a1;
    String[] a2;
    int a3;
    double a4;
    long a5;
}

And here is the main class:

public class Main
{
    public static void main(String[] args)
    {
        Object obj1 = new Object("example text", new String[] {"some", "more", "examples", "here"}, 1, 1.0);
    }
}

Error message:

java: constructor Object in class Object cannot be applied to given types; required: no arguments found: java.lang.String,java.lang.String[],int,double reason: actual and formal argument lists differ in length

4
  • 1
    Object is a built-in type. Call your class something else. And if you want to pass arguments to new, write a constructor in it. Commented Apr 20, 2022 at 8:16
  • Check also the javadocs: docs.oracle.com/javase/7/docs/api/java/lang/Object.html Commented Apr 20, 2022 at 8:19
  • Sorry, I used "Object" just as an example name to make it more understandable. In my actual code I used a different name. Commented Apr 20, 2022 at 8:20
  • Does this answer your question? Java Constructors Commented Apr 21, 2022 at 18:13

2 Answers 2

0

You must declare a constructor for your Object class inside it as:

public class Object {
    String a1;
    String[] a2;
    int a3;
    double a4;
    long a5;

    public Object(String example_text, String[] strings, int i, double v) {
    }
}

And another important thing is that Object is a predefined class in Java, so you should use full package name of your own Object class in main method:

public class Main
{
    public static void main(String[] args)
    {
        Object obj1 = new path.to.Object("example text", new String[] {"some", "more", "examples", "here"}, 1, 1.0);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nitpick: Object is not a keyword. But your point stands and your suggestion about namespacing it makes sense. Even better, don't import it but refer to it with its full package name to avoid confusion (var obj1 = path.to.Object("example text", new String[] {"some", "more", "examples", "here"}, 1, 1.0);). Even better-er don't call your own class Object :)
0

You should change the name of your class, since Java already has a class name Object or add a constructor for your Class. Use for example the name MyObject.java

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.