Calling a nested class from a different java source file?
I am pretty new to java, and I'm trying to write a simple program for practice, but it requires me to call a nested class from a different java source file, and I'm not sure how to do that... I don't think I need to post my code, but if I do need to, don't be afraid to ask.
Re: Calling a nested class from a different java source file?
I'm not sure what a nested class is. Could you post a small program that shows your problem?
Re: Calling a nested class from a different java source file?
Sure.
Code Java:
public class example{
public static void main(String[] args){
public class nestedClass{ /*This is what I meant*/
Re: Calling a nested class from a different java source file?
Does that compile? You show a class defined inside of a method
Have you looked in the Tutorial for nested classes?
http://download.oracle.com/javase/tu.../java/TOC.html
Re: Calling a nested class from a different java source file?
Oh! Thanks! I read a bit, then found this syntax: OuterClass.InnerClass innerObject = outerObject.new InnerClass();
Re: Calling a nested class from a different java source file?
Yup - the access specifiers (public, protected, private) work the same as for variables, but the OuterClass.InnerClass syntax is a bit messy - which is, perhaps, a hint that it's not expected to be a commonly used construct. More usually, the OuterClass is given a method that will return a new instance of the inner class (which can then be private or anonymous). An example of this is the iterator() method provided by List objects (e.g. ArrayList), that returns an instance of an inner Iterator class.
Re: Calling a nested class from a different java source file?
My personal beliefs are that if you have a nested/inner class then the purpose of that class is to be used by (and only by) the enclosing class. If the nested/inner class DOES need to used/accessed by another class then why the hell is it a nested/inner class in the first place? It should be a top level class in it's own right.
Re: Calling a nested class from a different java source file?
Quote:
Originally Posted by
Junky
My personal beliefs are that if you have a nested/inner class then the purpose of that class is to be used by (and only by) the enclosing class. If the nested/inner class DOES need to used/accessed by another class then why the hell is it a nested/inner class in the first place? It should be a top level class in it's own right.
True in general, but there are situations (e.g. anonymous Iterators, factory classes, etc.), where it just makes more sense to use an inner class that returns an interface implementation. That way, the implementation is kept private. With things like anonymous Iterators, it's a way of extending the API of the host/owner class without explicitly adding a whole bunch of methods to it.