Reputation: 23
public class Class1 {
public Class2 getClass2() {
//How can I implement this method?
}
public class Class2 {
//...
}
}
I just can't get it done, even though it should only be one line of code...
Upvotes: 1
Views: 73
Reputation: 3831
public class Class1 {
private Class2 class2 = new Class2();
public Class2 getClass2() {
return class2;
}
public class Class2 {
//...
}
}
Upvotes: 0
Reputation: 7863
I think you are getting the concept of inner classes wrong. In your example, you have a public inner class. That doesn't mean that your Class1
has exactly one object of Class2
. You can still create as many objects of Class2
as you like. If you want to do this outside of Class1
use new Class1.Class2()
. While this is possible, it would be bad design as galovics correctly mentioned in his answer.
If what you are trying to achieve is having one object reference to a Class2
object inside Class1
, use a field of type Class2
in Class1
and a matching getter method:
public class Class1 {
private Class2 class2instance = new Class2();
public Class2 getClass2() {
return class2instance;
}
private class Class2 {
//...
}
}
Upvotes: 0
Reputation: 3416
You should not do this. The inner class should be used in the outer class and not elsewhere. If you need an instance of the inner class then it should be not an inner class.
Upvotes: 1
Reputation: 1995
Just create a getter method in the outer class like this.
public class Class1 {
public Class2 getClass2() {
//How can I implement this method?
}
public Class2 getClass2() {
return new Class2();
}
public class Class2 {
//...
}
}
Upvotes: 0