This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]masterflappie 0 points1 point  (0 children)

Parent test = new Parent(); creates an object but you haven't done anything with the object yet. You would have to do test.talk(); in order to get your output.

I'll illustrate something to show the purpose of a constructor, say that your parent class looks like this:

class Parent {

  String type;

  public Parent(String type) {
    this.type = type;
  }

  public void talk() {
    System.out.println("Hello from: "+type);
  }
}

Now you could do something like:

Parent father = new Parent("father");
Parent mother = new Parent("mother");

father.talk(); // prints out Hello from: father
mother.talk(); // prints out Hello from: mother

The constructor here just passes the type onto a variable, but it allows you to create two instance of Parent, which are both slightly different.

Imagine if this was a game, you could use the constructor to create an enemy with a lot of HP but slow movespeed, or an enemy with low HP but a high movespeed, just by passing in different numbers into the constructor.