[Java] [Java] Writing when passing two or more arguments to super

1 minute read

What is super?

If this is not understood in the first place, it feels like something is wrong.

Apparently it is a method from an image perspective.

I don’t know if it’s correct, but I found only the explanation such as ~ used at times and so on when I looked it up.

If you think that it is a ### method, it is easy to imagine how to write the argument.

I don’t know what happens when I use super, so I write this way and I get an error

public class Oya {
  private String name;
  private int score;
  
// constructor
  public Oya(String name, int score) {
    this.name = name;
    this.score = score;
  }

  // getter that allows you to read the value of the variable from the child class
  public String getName() {
    return this.name;
  }
  
  // getter that allows you to read the value of the variable from the child class
  public int getScore() {
    return this.score;
  }
}

public class Ko extends Oya {
  // child class constructor
  public Ko() {
    // super(name); // ← no
    // super(score); // ← no
    super(name, score); // Write as you would when passing arguments to a method
  }

  public void sayHello() {
    // name is private in Oya class, so you cannot access it with this.name etc.
   // If you write a getter in Oya class, it will return the value of name using the method
    System.out.println("hello! "+ this.getName()); // ← Call the getName method of the Oya class at the end and receive the value of name
  }
}

public static void main(String[] args) {
  Ko bob = new Ko("bob", 10);
  Ko.sayHello();
}

This worked. If you write super(name, score), the compilation error will disappear and the constructor will work properly.

Pass two or more arguments like ###super (argument 1, argument 2)

I just couldn’t think of how to write it, and the usage example of super only came out with one argument, so I will leave it as a note.

I mistakenly thought that I would pass variables one by one to the constructor of Oya class by writing super (argument).

This is an amateur article, so please point out any mistakes.

Tags:

Updated: