0

I would like to create one class and then another class inside. This class will be directly connected with superior class. It should look like following (not code, just schema):

class company
    string name

    class employee
        string firstName, lastName;
        int age

Of course, I have constructors etc. Now I want to create company 'g' and employee f m of age 2 inside of that company. Maybe it is not justified to make class inside another class and I should just create class employee with field company?

Code below does not work, compiler says: an enclosing instance that contains company.employee is required

  nowa=new company('g',2);
 nowa.prac=new company.employee('f','m',2);

Full code below:

public class program
{
public static class company
{
    char name;
    int duration;

    public class employee
    {
        public char imie,nazwisko;
        public int wiek;
        public employee(char a,char b,int w)
        {
            imie=a;
            nazwisko=b;
            wiek=w;
        }
    }
    public company(char n,int c)
    {
        name=n;
        duration=c;
    }
}



 public static void main(String []args)
 {
     company nowa=new company('g',2);
     nowa.empl=new employee('f','m',2);
 }
 }
user3162968
  • 1,016
  • 1
  • 9
  • 16

3 Answers3

0

try

nowa.prac = nowa.new firma.pracownik('f','m',2);

Here is more on why:

http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Senad Uka
  • 1,131
  • 7
  • 18
0

This would be my approach

public class Employee {

  //...code
}

public class Company {
 //...code
 private List<Employee> employees;
}


public static void main(String []args)
 {
     Company nowa=new company('g',2);
     nowa.getEmployees.add(new Employee('f','m',2));
 }
 }

The main changes from your approach are:

  1. Both classes are in its own file (both are top level classes).
  2. Company has an List of Employees (a company HAS employees). With a List you can add and remove easily employees for a given Company.
  3. Class names are capitalized (according to Java naming conventions by using Upper Camel Case).
Averroes
  • 4,168
  • 6
  • 50
  • 63
0

Your inner class employee is not static, so you need an instance of the outer class to create an inner class instance. An employee may not exist without a company!

company nows = new company('g',2);
nowa.empl = nowa.new employee('f','m',2);

In this case the inner class instances have an implicit reference to the outer class instance (use company.this inside employee to access it).

If you want to make the classes more independent, you can make employee a status inner class without the reference to the outer class:

public static class employee
...

company nows = new company('g',2);
nowa.empl = new employee('f','m',2);
Arne Burmeister
  • 20,046
  • 8
  • 53
  • 94