Caleb Hyun
Caleb Hyun

Reputation: 69

Something is wrong in a constructor of a class

This program requires for a user to enter twice of name and employmentId, while it has to require just once.

I am trying to print a sentence using name and employmentId instance variables which are inherited to a class named Nursing. The program ran well. However, the problem is that it requires a user to input twice for name and employmentId.

AbstractTest.java -

import java.util.*;

class AbstractTest {
    String name;
    int employmentId;

    AbstractTest (){
        //initialize name and employmentId instance variables
        System.out.println("enter name");
        Scanner readString = new Scanner(System.in);
        this.name = readString.nextLine();

        System.out.println("enter ID");
        Scanner readInt = new Scanner(System.in);
        this.employmentId = readInt.nextInt();
    }
    // constructor ends
}

Nursing.java -

class Nursing extends AbstractTest{
    void display() {
        System.out.println("the employment detail: " + "Name: " + 
        name + "ID: " + employmentId);
    }
}

Main.java -

class Main {
    public static void main(String[] args) {
        AbstractTest abstractTest = new AbstractTest();
        Nursing nursing = new Nursing();
        nursing.display();
    }
}

//It runs well, but it somehow repeats twice for inputting name and ID. it should require just once (below is the result from MS DOS).

enter name Batman

enter ID 1234

enter name Superman

enter ID 5678

the employment detail: Name: SupermanID: 5678

Upvotes: 1

Views: 86

Answers (3)

Prashant Pandey
Prashant Pandey

Reputation: 4642

When you create a Nursing object, it implicit empty construct calls the super no-args constructor. So AbstractTest constructor is being called two times - once when you create its object, and other when you create a Nursing object.

Object creation while using inheritance is a bit complex and I suggest you read on it.

Upvotes: 1

Andrew
Andrew

Reputation: 49646

Remove the line

AbstractTest abstractTest = new AbstractTest();

Although you don't work with that object, it's being created and the Scanner is requesting 2 inputs.

Nursing nursing = new Nursing();

is enough: it will call its parent's constructor, which is the one of AbstractTest.

Upvotes: 3

dumbPotato21
dumbPotato21

Reputation: 5695

This line

Nursing nursing = new Nursing();

automatically calls the constructor of the super class, that is AbstractTest(). You don't have to call it explicitly by creating an object of AbstractTest

Thus, simply remove the line

AbstractTest abstractTest = new AbstractTest();

If you don't remove it, the constructor is run twice, and thus you have to give the input twice as well.

Upvotes: 1

Related Questions