Venkata Sridhar Sai
Venkata Sridhar Sai

Reputation: 31

How can we create an instance for a nested class in array of objects in java?

import java.util.Arrays;
import java.util.Scanner;

public class employee{
    public String name;
    public class employee_address{
        String street_name;
        String city;
        String zipcode;
        String state;
        String country;
    }

    public static void main(String []args){
        Scanner user_input = new Scanner(System.in);

        int no_of_employees = user_input.nextInt();
        employee[] employees_list = new employee[no_of_employees];
        for(int i = 0;i < no_of_employees;i++){
            employees_list[i].name = user_input.nextLine();
            employees_list[I].employee_address = // this is it ? 
        }
    }
}

In the code above I do understand that the employee_address is a class and can't be accessed directly without an instance being created like in the code, that makes no sense. but how can I create an instance of the employee_address class that is associate with each employee.

like in the code above 'employee_address' is associated with every employee but how can the class 'employee_address' be initialised and how can I set the street_name, city and the rest of the members in the address class. any ideas would be appreciated.

Upvotes: 0

Views: 1257

Answers (3)

Abra
Abra

Reputation: 20924

Below code uses Java naming conventions (which your code does not).

Notes after the code.

import java.util.Scanner;

public class Employee {
    private String name;
    private EmployeeAddress address;

    public class EmployeeAddress {
        String streetName;
        String city;
        String zipcode;
        String state;
        String country;
    }

    public static void main(String[] args) {
        Scanner userInput = new Scanner(System.in);
        int noOfEmployees = userInput.nextInt();
        Employee[] employeesList = new Employee[noOfEmployees];
        for (int i = 0; i < noOfEmployees; i++) {
            employeesList[i] = new Employee();
            employeesList[i].name = userInput.nextLine();
            EmployeeAddress employeeAddress = employeesList[i].new EmployeeAddress();
            employeesList[i].address = employeeAddress;
            employeesList[i].address.streetName = userInput.nextLine();
        }
    }
}

An inner class is a normal class. It is not a member of its enclosing class. If you want class Employee to have an [employee] address, as well as a [employee] name, you need to add another member variable to class Employee whose type is EmployeeAdress.

Employee[] employeesList = new Employee[noOfEmployees];

The above line creates an array but every element in the array is null. Hence you need to first create a Employee object and assign it to an element of the array. Hence the following line in my code, above:

employeesList[i] = new Employee();

Since EmployeeAddress is not a static class, in order to create a new instance, you first need an instance of the enclosing class, i.e. Employee. Hence the following line in the above code.

EmployeeAddress employeeAddress = employeesList[i].new EmployeeAddress();

Since all your code is in class Employee, in method main you can directly access the members of both class Employee and EmployeeAddress. Nonetheless you need to be aware of the different access modifiers in java.

Upvotes: 1

Papai from BEKOAIL
Papai from BEKOAIL

Reputation: 1539

You can't directly create an instance of inner class, the reason because since it is the property of another instance we always need to use it though the instance of parent variable.

Let's say you have a class, which have two propeties:

public class Employee {
    public String name;
    public EmployeeAddress emAddress;
}

to access emAddress you need to use through the instance of Employee class, for example -

Employee object = new Employee();
EmployeeAddress empAdd = object.new EmployeeAddress();

Full code:

public class Employee {
    public String name;
    public EmployeeAddress emAddress;

    public class EmployeeAddress {
        String street_name;
        String city;
        String zipcode;
        String state;
        String country;
        public String getStreet_name() {
            return street_name;
        }
        public void setStreet_name(String street_name) {
            this.street_name = street_name;
        }
        public String getCity() {
            return city;
        }
        public void setCity(String city) {
            this.city = city;
        }
        public String getZipcode() {
            return zipcode;
        }
        public void setZipcode(String zipcode) {
            this.zipcode = zipcode;
        }
        public String getState() {
            return state;
        }
        public void setState(String state) {
            this.state = state;
        }
        public String getCountry() {
            return country;
        }
        public void setCountry(String country) {
            this.country = country;
        }
        @Override
        public String toString() {
            return "EmployeeAddress [street_name=" + street_name + ", city=" + city + ", zipcode=" + zipcode
                    + ", state=" + state + ", country=" + country + "]";
        }
        
        
    }

    public static void main(String[] args) {
        Scanner user_input = new Scanner(System.in);

        int no_of_employees = user_input.nextInt();  // let's say no_of_employees =  1
        Employee[] employees = new Employee[no_of_employees];
        for (int i = 0; i < no_of_employees; i++) {
            Employee object = new Employee();
            object.setName("Virat Kohli");
            
            EmployeeAddress empAdd = object.new EmployeeAddress();
            empAdd.setCity("New Delhi");
            empAdd.setCountry("India");
            empAdd.setState("Delhi");
            empAdd.setStreet_name("Chandni Chalk");
            empAdd.setZipcode("741124");
            
            object.setEmAddress(emAddress);
            employees[i] = object;          
        }
        
        System.out.println(employees[0]);
        
        user_input.close();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public EmployeeAddress getEmAddress() {
        return emAddress;
    }

    @Override
    public String toString() {
        return "Employee [name=" + name + ", emAddress=" + emAddress + "]";
    }

    public void setEmAddress(EmployeeAddress emAddress) {
        this.emAddress = emAddress;
    }
}

I have modified your code to sonar standard.

Upvotes: 2

JayC667
JayC667

Reputation: 2588

A few hints:

  1. stick to naming conventions: class names in Java start with capital letters
  2. use (class) definitions before using them (collect them at the top if not inconventient)
  3. if you are sure you want to use inner classes, set them static, unless you want them to be entangled in generics.
  4. Usually normal classes in each their own file are a lot more flexible and far easier to use
  5. if you use objects that only carry public data, try to use final keyword and initialize them ASAP
  6. use proper objects first, and after finishing them assign them to arrays. avan better would be the use of ArrayList and the like
  7. if Employee contains EmployeeAddress, it should initialize it if conventient. so an object is always responsible for its own stuff
  8. Use try/resrouce/catch
  9. scanner.nextInt() can be problematic with newline/line breaks. For user input better readLine() and parse input

Code:

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;

public class Employee {


    static public class EmployeeAddress {
        public final String street_name;
        public final String city;
        public final String zipcode;
        public final String state;
        public final String country;
        public EmployeeAddress(final Scanner pScanner, final PrintStream pOutPS) {
            street_name = readLine(pScanner, pOutPS, "Please enter Street Name:");
            city = readLine(pScanner, pOutPS, "Please enter City Name:");
            zipcode = readLine(pScanner, pOutPS, "Please enter Zip Code:");
            state = readLine(pScanner, pOutPS, "Please enter State:");
            country = readLine(pScanner, pOutPS, "Please enter Country:");
        }
    }

    static public String readLine(final Scanner pScanner, final PrintStream pOutPS, final String pPrompt) {
        pOutPS.print(pPrompt);
        final String value = pScanner.nextLine();
        pOutPS.println();
        return value;
    }
    static public int readInt(final Scanner pScanner, final PrintStream pOutPS, final String pPrompt) {
        return Integer.parseInt(readLine(pScanner, pOutPS, pPrompt));
    }



    public final String             name;
    public final EmployeeAddress    address;

    public Employee(final Scanner pScanner, final PrintStream pOutPS) {
        name = readLine(pScanner, pOutPS, "Please enter Employee Name: ");
        System.out.println("Name: " + name);
        address = new EmployeeAddress(pScanner, pOutPS);
    }



    public static void main(final String[] args) {
        try (final Scanner user_input = new Scanner(System.in);
                final PrintStream output = System.out;) {

            final int no_of_employees = readInt(user_input, output, "Please enter number of users: ");

            final Employee[] employees_list = new Employee[no_of_employees]; // either this line
            final ArrayList<Employee> employees = new ArrayList<>(); // or this line

            for (int i = 0; i < no_of_employees; i++) {
                output.println("Creating user #" + (i + 1) + "...");
                final Employee newEmployeeWithAddress = new Employee(user_input, output);

                employees_list[i] = newEmployeeWithAddress; // either this line
                employees.add(newEmployeeWithAddress); // or this line
            }

        }
    }



}

Upvotes: 0

Related Questions