Home > Enterprise >  How Can I Fix My Program So That I Have Super as First Statement in Constructor?
How Can I Fix My Program So That I Have Super as First Statement in Constructor?

Time:07-08

I tried getting rid of void from the constructor in Hero class, but Visual Studio Code told me to include a return type. I have the super keyword as the first statement in the constructor, but keep getting the same error. Any help on how to fix this would be appreciated. Thx

Here's my code:

public class testJava
{
    public static void main(String[] args) {
        Hero h1 = new Hero();
        Hero h2 = new Hero();
        Hero.name = "Spiderman";

        System.out.println(h1.toString());
        System.out.println(h2.toString());
    }
}

public class People {
    static String name;
    int age;

    static {
        name = "Acquaman";
    }
    public People(String name, int age)
    {
        this.name = name;
        this.age= age;
    }

    public String toString(){
        return this.name   " is "   this.age   " and has ";
    }
}

public class Hero {
    public static String name;
    String power;

    
    public void Hero(String name, int age, String power)
    {
        super(name, age);
        this.power = power;
    }

    public String toString()
    {
        return super.toString()   this.power   " as power.";
    }
}

CodePudding user response:

By definition, constructor must have the same name as the class and no return type. In your case, the class is called Hero, but you're trying to use Human for constructor name.

CodePudding user response:

The super() constructor is always implicitly called. if you want to explicitly call it use super() with the appropiate arguments as a first statement inside your child constructor (don't forget to extend People if you are messing around with inheritance), this must be done after what @jurez stated in their answer.

  • Related