[英]Java class inside other class, constructor
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 fm of age 2 inside of that company. 当然,我有构造函数等。现在我想在公司内部创建公司'g'和2岁的员工fm。 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 编译器说,下面的代码不起作用: 包含company.employee的封闭实例是必需的
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);
}
}
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 http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
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: 您的方法的主要变化是:
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). 在这种情况下,内部类实例具有对外部类实例的隐式引用(使用company.this内部雇员访问它)。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.