An enclosing instance that contains <my reference> is required - java

An enclosing instance that contains is required
Below is the code. positionObj is the object that I am trying to use and it is giving me the above error.
It's unclear why.
package toolBox;
import toolBox.Secretary.positionObj;
public class PositionManagement {
public static HashMap<String, Secretary.positionObj> main(String vArg){
positionObj newPosition=new positionObj();
}
}

You're trying to use the non-static inner positionObj class without an instance of Secretary for it to belong to.
A non-static inner class must belong to an instance of its parent class
You should probably change positionObj to a normal class or a static inner class.
Alternatively, you can write someSecretary.new positionObj() to create an instance of the inner class that belongs to the someSecretary instance.

First create an object of Outer class. In this case I think "Secretary". Then create positionObj. Like this,
Secretary x = new Secretary();
Secretary.positionObj y = x.new positionObj();

The correct generic signature would be
public static HashMap<String, positionObj> main(String vArg)
you dont need to qualify positionObj since you already import it.
However, I am pretty sure a main method must conform to the signature below. If you intend to have main be the main method for your program, change the signature to
public static void main(String[] args) {...}
you can create a separate static method that returns a Map and invoke it from main.
As a note, all classes should begin with a capital letter, positionObj, should be PositionObj.

Related

newInstance() with inner classes

I've been working on an instantiation method that will allow me to package a variety of similar classes into one outer class. I could then instantiate each unique class type by passing the name of that type to the constructor. After a lot of research and errors, this is what I have come up with. I have left an error, to demonstrate my question.
import java.lang.reflect.Constructor;
public class NewTest
{
public static void main(String[] args)
{
try
{
Class toRun = Class.forName("NewTest$" + args[0]);
toRun.getConstructor().newInstance();
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
public NewTest(){}
private class one //Does not instantiate
{
public one()
{
System.out.println("Test1");
}
}
private static class two //Instantiates okay
{
public two()
{
System.out.println("Test2");
}
}
}
Compiling this code and running java NewTest two results in the output Test2, as I intended.
Running java NewTest one results in
java.lang.NoSuchMethodException: NewTest$one.<init>()
at java.lang.Class.getConstructor(Unknown Source)
at java.lang.Class.getConstructor(Unknown Source)
at NewTest.main(NewTest.java:12)
I'm confused about this because, as far as I know, I am referencing an inner class correctly, an outer class should have access to an inner class, and I have a default no arg constructor.
Non-static inner classes need an instance of the outer class to work properly. So, they don't "really" have a default constructor, they always have a kind of hidden parameter in which they expect an outer class instance.
I don't know why you want to have them all in a single class. If you are doing this so that it's only one file, put them in a package and in separate classes. Having less files does not make your program better.
If instead you need them to share something, so the outer class will work as a kind of "scope", you can still do that without using inner classes, but by passing them a context of some sort.
If you really really want to instantiate the inner class, you need to use the hidden constructor taking the outer class as a parameter :
NewTest outer = new NewTest();
Class<?> toRun = Class.forName("NewTest$" + args[0]);
Constructor<?> ctor = toRun.getDeclaredConstructor(NewTest.class);
ctor.newInstance(outer);
A non-static inner class cannot be instantiated without an instance of its parent class.
new NewTest().new one()
The call above will successfully instantiate a one.
Your two is being instantiated without an outer instance, because of the static modifier. It is a static nested class.
See the difference between static nested classes and inner classes: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
You need to make class one static. Non-static nested classes must be instantiated with an instance of the containing class.

Can a static nested class be instantiated in Java?

From Oracle's Java tutorials I've found this text:
As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class — it can use them only through an object reference.
Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
I thought it is not possible to instantiate a static class, so I don't really understand the sentence in bold.
Do you have any idea what it means?
You are either confusing static with abstract as kihero says, or you are muddling the concept with a class that has static methods (which is just a class that happens to have static methods).
A static nested class is just a nested class that doesn't require an instance of its enclosing class. If you are familiar with C++, all classes in C++ are "static" classes. In Java, nested classes are not static by default (this non-static variety is also called an "inner class"), which means they require an instance of their outer class, which they track behind the scenes in a hidden field -- but this lets inner classes refer to fields of their associated enclosing class.
public class Outer {
public class Inner { }
public static class StaticNested { }
public void method () {
// non-static methods can instantiate static and non-static nested classes
Inner i = new Inner(); // 'this' is the implied enclosing instance
StaticNested s = new StaticNested();
}
public static void staticMethod () {
Inner i = new Inner(); // <-- ERROR! there's no enclosing instance, so cant do this
StaticNested s = new StaticNested(); // ok: no enclosing instance needed
// but we can create an Inner if we have an Outer:
Outer o = new Outer();
Inner oi = o.new Inner(); // ok: 'o' is the enclosing instance
}
}
Lots of other examples at How to instantiate non static inner class within a static method
I actually declare all nested classes static by default unless I specifically need access to the enclosing class's fields.
Static nested classes are themselves not static at all. In java, no class is static. Static keyword in static nested classes implies that it is another static member of the outer class. But it is just another raw class . Thats why we can instantiate this class
You are confusing static with abstract. Abstract classes can not be instantiated. static is not a valid qualifier for top level classes, but the meaning for inner classes is the one you quoted.
I guess you misunderstood the static class a little bit.
It's true that every abstract class and interface cannot be instantiated, but you do can instantiate an static class.
One thing you should notice is that every static class is a nested static class.
You cannot just create a static class, as you can see:
try to create a new class in eclipse
A static class always belongs to the "parent class" which encloses it, and the difference between static and non-static class is:
You can refer to the child static class just like a static property of the "parent class":
ParentClass.NestedStaticClass nestedstatic = new ParentClass.NestedStaticClass();
but you can only make reference to the non-static nested class by instantiating a parent class, like this:
ParentClass parent = new ParentClass();
ParentClass.NestedClass nested = parent.new NestedClass();
The difference is just like that between the static and non-static field.
Too long, didn't read: Every Concrete Class can be instantiated.
We should not expect a Concrete Static Nested Class to function identically as Static variables and Static methods, when it comes to calling and instantiation.
What do I mean by that? When we create variables and methods they can be either static or non-static. The keyword in the previous sentence is "either".
Static meaning they belong to the class and we must call them directly, like this:
Class.staticVariable();
Class.staticMethod();
Non-static meaning they belong to an Instance of that Class and we must call them like this:
Class obj = new Class();
System.out.println(obj.nonStaticVariable);
obj.nonStaticMethod();
But here we are talking about a Class, not a variable or a method.
Every Concrete Class can be instantiated. Thus we should not expect a Concrete Static Nested Class, to not be instantiable.

Static nested classes

I'm reading 'Thinking of Java' and I have encountered some weird example (for me)
class StaticTest {
static class StaticClass {
int i = 5;
}
}
public class I {
public static void main(String[] args) {
// TODO Auto-generated method stub
StaticTest.StaticClass t = new StaticTest.StaticClass();
}
}
How is it possible to create instance of static class? Is it some exception to the rule 'You can't create instance of static class'?
Thanks in advance
In case of classes, the modifier static describes the relationship between the outer and the inner class.
If the inner class is not static, it is bound to an instance of the outer class and threrefore cannot be created from outside.
A static inner class can completely be created without an instance of the outer class, but has privileged access to members of the class.
A static class is nothing more than a class, but with the difference to where it's code is placed.
Therefore, you can create instances of static classes. The only difference is you have to provide the name of the class, which nests the static one (as shown on your code snippet).
StaticTest.StaticClass t = new StaticTest.StaticClass();
From Java docs regarding creating instance for static nested classes.
And like static class methods, a static nested class cannot refer directly to instance
variables or methods defined in its enclosing class — it can use them only through an
object reference.
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
in this case static describes the relation b/w inner and outer class
it doesnt mean the inner class is static
a static nested class doesnt invoke non-static methodes or access non-static fields of an instance of class within which it is nested

Java nested classes issue

As I have recently started programming, I was a little stuck in this area of coding.
There is a programming lesson named nested classes. But when I want to use it, it actually does not do what the homework wants. Here is an example of what I need to achieve:
public class Zoo {
...
public static class monkey {
...
}
}
and in the main
Zoo zoo1 = new Zoo();
...
zoo1.monkey.setage(int);
...
But there is a problem here that whenever I want to call monkey from zoo1, the debugger says that it's not possible.(Remember that I want to do this without creating an instance of monkey)
Thanks in advance
Update: I am just wondering if it's a kinda language limitation, then how the oracle itself could do that rather easily with system.out.printf?
You can not access the monkey class via an instance of Zoo, it would not actually make any sense to do that. If you want to access static methods of monkey from the main you can just use the example below
public class Zoo {
public static void main(String[] args) {
// Example 1
monkey.setage(3);
// Example 2
Zoo.monkey.setage(3);
}
public static class monkey {
private static int age;
public static void setage(int age) {
monkey.age = age;
}
}
}
But what are you actually trying to accomplish?
monkey looks static to me. They should be public instead of Public, though.
I would say that setage() is not a static method. If that's the case, and if age is a property of a monkey, than it wouldn't make sense to call it statically -- whose age would you be setting?
The problem though is that you can't seem to be able to access the static inner class through a variable of the outer class type.
So it should be Zoo.monkey instead of zoo1.monkey.
If you just want to control scoping or naming, you can use packages.
For example, you could have the following:
package com.example.application.feature;
public class MyClass {
public void f() {
System.out.println("Hello");
}
}
in a source file called com/example/application/feature/MyClass.java.
Edit: I didn't see you note "(Remember that I want to do this without creating an instance of monkey)"
sometimes before asking, searching might help you to save some time.Direct Quotion from this address: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Inner Classes
As with instance methods and variables, an inner class is associated
with an instance of its enclosing class and has direct access to that
object's methods and fields. Also, because an inner class is
associated with an instance, it cannot define any static members
itself.
Objects that are instances of an inner class exist within an instance
of the outer class. Consider the following classes:
class OuterClass {
...
class InnerClass {
...
} }
An instance of InnerClass can exist only within an instance of
OuterClass and has direct access to the methods and fields of its
enclosing instance. The next figure illustrates this idea.
An Instance of InnerClass Exists Within an Instance of OuterClass
To instantiate an inner class, you must first instantiate the outer
class. Then, create the inner object within the outer object with this
syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
Additionally, there are two special kinds of inner classes: local
classes and anonymous classes (also called anonymous inner classes).
Both of these will be discussed briefly in the next section.

Java - Using Instance Class from Static Method?

I've been programming for years using .NET and I'm taking the plunge into Java with some simple starter programs.
I'm having a bit of trouble though...
When I create my start-up class with public void main, the compiler won't let me instantiate any of the classes I've written?
The error I'm getting is "non-static variable _processor cannot be referenced from a static context" where _processor is the object I'm trying to instantiate from the Processor class that I wrote.
The program will compile and run just fine when I change Processor to a static class, but I don't want to have to make all of my classes static.
Any way around this?
Thanks in advance!
Here's everything I've written. It won't compile in the current state:
class Lab
{
public static void main(String[] args)
{
Processor proc = new Processor();
proc.Go();
}
private class Processor
{
private Random _rand = new Random();
public void Processor() {}
public void Go()
{
}
}
}
Is Processor an inner class of Lab by any chance? (yes, now that you published your code, my suspicion is confirmed).
In Java, nonstatic inner classes contain an implicit reference to the containing object of the outer class, so they can't be instantiated from static context (from your main method).
So
either create an instance of Lab (e.g. myLab), and then call myLab.new Processor(), or
declare Processor static (as you did), or
turn Processor into a top level class.
Is this your problem, by any chance?
public class DemoClass{
String field;
public static void main(String[] args){
field = "Hey"; //forbidden - can't access instance field from static context
DemoClass dc = new DemoClass();
dc.field = "Hey"; //this is ok
}
}
You should call a constructor from main:
public static void main(String[] args){
new MyClass();
}
And put your instantiations in the constructor.
but I don't want to have to make all of my classes static.
Most inner classes in Java are static, in my experience. If you can write an inner class in a separate file (it does not use directly the members of the containing class), it should then be defined as static. It really is only for convenience that Java lets you write inner static classes inside other classes.
Your process class is an inner class of your lab class, you can't create an instance of your process class until you instantiate an instance of you lab class, unless that inner class is static or something.
Main will run in your lab class, because it is static, but when you attempt to create an instance of the private inner class, you can't because this class is a "private inner" class of Lab, and you don't have a lab instance, so you can't reference it directly.
You can try making your processor class static, or at the very least public, or better yet you can instantiate an instance of your lab class first, and reference creation of the processor class through your instantiate lab class.

Categories