Home > front end >  Java : constructor error "method 'void <init>()' not found"
Java : constructor error "method 'void <init>()' not found"

Time:05-19

In main method, I create a new object with a non-argument constructor. But I have runtime error on this line.

Could you please explain why?

class Student {
    String name;
    int age;

    Student() {
        Student();
    }

    void Student() {
        Student("James", 25);
    }

    void Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class Test_03_09 {
    public static void main(String[] args) {
        Student s = new Student(); // Runtime error
        System.out.println(s.name   ":"   s.age); 
    }
}

CodePudding user response:

As there are so many bad answers:

It boils down to simply use correct syntax for the Student class constructors:

class Student {
    String name;
    int age;

    Student() {
      this("James", 25);
    }

    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

Note: the "runtime error" is most likely an artefact of the whole code NOT compiling, and your IDE doing the wrong thing.

CodePudding user response:

Constructors don't have return values, not even void. You've created methods, not constructors.

  • Related