Hello, I'm creating a subclass from an already defined class. Let's say I have a class called Student and it has a default constructor. Now I want to create a child class of Student, but when I create it, it seems that it's taking the constructor instead of the actual class name

public class Member extends Student {
}

What can I do to fix this?

Dani AI

Generated

The behaviour comes from how Java handles constructors: if a superclass defines any constructor and does not supply a no-argument (default) constructor, the compiler will not create one for you. A subclass that relies on the compiler-generated no-arg constructor will therefore fail at compile time because the implicit call to super() has no matching constructor in the superclass. Common compiler messages include "implicit super constructor Student() is undefined" or "constructor Student in class Student cannot be applied to given types".

Two safe ways to fix this:

public class ClubMember extends Student {
    public ClubMember(int age) {
        super(age);    // explicitly call the Student constructor that takes an int
        // subclass initialization here
    }
}

or add a no-arg constructor to the superclass if that makes sense for your design:

public class Student {
    public Student() { }
    // other constructors stay here
}

Extra troubleshooting notes: ensure a constructor has no return type (writing public void Member() makes it a method, not a constructor). If the superclass constructor has restricted visibility (private), a subclass in another package cannot call it — change it to protected or public if appropriate. Also confirm the public class name matches the filename. As pointed out, this topic is commonly discussed; reviewing Java constructor rules (for example, Oracle's "Constructors" tutorial) clarifies why the explicit super(...) or a no-arg superclass constructor is required. This is the reason behind the behaviour you observed, .

Recommended Answers

All 3 Replies

class student looks like this

public class Student {
  int age;
  public Student (int age){
       this.age = age;
  }
}

Thanks for the link, and sorry I missed it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.