Search for errors in a given code block (class extension, person / student)

There are several (alleged) errors in the next block of code, and my task is to find them and explain whether errors can lead to problems when compiling the code, or at least to some logical problems.

public class Person {

  private String name;

  public Person(String name) {

    name = name;

  }

  public String toString() {

    return "Name: " + name;

  }
}

public class Student expands Person {

  private int Nr;

  public Student(String name, int Nr) {

    name = name;

    Nr = Nr;

  }

   public String toString() {

   return toString() + " Nr: " + Nr;

  }
}

As far as I can see, the first errors are in the fourth line of the class Person. While name = nameit should not lead to a compilation error, it should give logical problems, since the formal parameter of the constructor namesuperimposes the object variable namethat we defined in advance. Actual code will be this.name = name.

In addition, I do not see any problems in the classroom Person.

"" - expands, extends. .

Student name = name. , / . , - ? , , super(name), name Person.

, this.Nr = Nr.

, : toString() + ..., , , , toString() .

, ?

+4
2

.

Student

public Student(String name, int Nr) {
    name = name;   
    Nr = Nr;
}

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

, name , Student.

:, , Nr N, . . .


@Julian,

public Student(String name, int Nr) {
    super(name);
    this.Nr = Nr;
}

, . . , Student .

+4

Student . Person.

person ( ), .

, , . . - ,

public Student(String name, int Nr) {
  super(name);
  name = name; // This don't make sense. Its like assigning name to name itself
  Nr = Nr;    // This is same as above. Has no effect.

}

StackOverflowError toString.

!!!

+1

Source: https://habr.com/ru/post/1670390/


All Articles