The Error "No Closing Instance..." [duplicate] - java

This question already has answers here:
What causes error "No enclosing instance of type Foo is accessible" and how do I fix it?
(11 answers)
Closed 8 years ago.
I am new at Java and lately I study class and object topics. However, I could not progress of this code:
public class ClassStudy {
// Student Group
class Student {
public String name = null;
public String surname = null;
boolean study(boolean does) {
// He studies.
boolean d = does;
return d;
}
boolean slackOff(boolean does) {
// He slacks off.
boolean d = does;
return d;
}
}
// Teacher Group
class Teacher {
public String name = null;
public String surname = null;
boolean teach(boolean does) {
// He teaches.
boolean d = does;
return d;
}
boolean learn(boolean does) {
// He learns.
boolean d = does;
return d;
}
}
// Main Method
public static void main(String[] args) {
Student student = new Student();
Teacher teacher = new Teacher();
}
}
In main method, I got errors of student, yet did not got of teacher. I do not know if I have done any mistake or I can not see it. What has to be done?
The errors I get:
The value of the local variable student is not used
No enclosing instance of type ClassStudy is accessible. Must
qualify the allocation with an enclosing instance of type ClassStudy
(e.g. x.new A() where x is an instance of ClassStudy).
Line breakpoint:ClassStudy [line: 44] - main(String[])

Either make the Student (and Teacher) class static or make it a top level class
static class Student {
...
}

The error already states the problem:
No enclosing instance of type ClassStudy is accessible. Must qualify
the allocation with an enclosing instance of type ClassStudy (e.g.
x.new A() where x is an instance of ClassStudy).
You cannot create instances of inner classes without having an instance of their surrounding class, except when they're static.
So what you need to change your main method to:
// Main Method
public static void main(String[] args) {
ClassStudy classStudy = new ClassStudy();
Student student = classStudy.new Student();
Teacher teacher = classStudy.new Teacher();
}
The reason you're not getting that same error on the line where you initialize Teacher, is because the compiler stops compiling at the first error it finds.

Reimeus has a correct solution. To understand what the message was telling you, you should read up on what static and non-static inner classes are. These should get you started.
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Java inner class and static nested class

Related

When does the members of the class initialize? [duplicate]

This question already has answers here:
Java order of Initialization and Instantiation
(2 answers)
Closed 3 years ago.
Exactly when the Class members are initialized ?
In below code:
public class A{
public B b = new B();
private C c = new C(123);
public A (arg a){
// Do something
}
public someMethod(){
Log.i(TAG, " "+ b.getD());
}
}
main(){
A a = new A ("xyz"); }
When would be the Object of Class B & C created? And is it guaranteed to be created?
Should a professional app use such code or not ?
You can analyze the question this way:
class Scratch {
public static void main(String[] args) {
A a = new A ("xyz");
}
}
class A{
public B b = new B();
private C c = new C(123);
public A (String a){
System.out.println("new A()");
}
}
class B {
public B() {
System.out.println("new B()");
}
}
class C {
public C(int i) {
System.out.println("new C()");
}
}
which executes giving the following output:
new B()
new C()
new A()
which matches wiith the answer of #Jakir Hossain.
So: inline fields initializers are executed before code in constructor, following the same order which they are declared in.
Instances of classes B and C are created on A's instance creation, before A's constructor is executed. This ordering (and fields' initialization) are guaranteed.
When an object is created, the following things are done in the following order:
The object is allocated on the heap with the correct object type,
and all instance fields are "default initialized" to zero, false or
null.
The expressions in the super(...) or this(...) are evaluated and the
constructor for the next class up the chain is called. (This
recurses up the chain constructor, so that the Object constructor
gets executed first.)
The instance variable initializers and any instance initializer
blocks are executed in order.
The body of the constructor is executed.
The constructor returns.
Hope it helps you.

Accessing static member by static object

Its said that, statics are much comfortable with statics in java. I'm trying to achieve small thing there where I want to change outer's class static variable value using inner static class's instance for that specific instance only. I think its a ideal case. If not please share with me. And moreover all inner classes have access to outer class's members.
So here is my code.
package org;
import org.Outerclass.innerclass;
public class Outerclass {
static String name = "Europe";
String getname() {
return name;
}
public void setname(String name) {
this.name = name;
System.out.println(this.name);
}
void setstaticname() {
Outerclass.innerclass i = new Outerclass.innerclass();
i.name = "London"; // Error "name cannot be resolved or is not a field" ?
System.out.println(i.name);
}
static class innerclass {
void updatename() {
Outerclass o = new Outerclass();
o.setname("USA");
}
}
public static void main(String[] args) {
innerclass p = new innerclass();
System.out.println(p.name); // Error "name cannot be resolved or is not a field" ?
}
}
I have tried in two ways and vice versa but same errors. Any suggestions ?
name is a member of OuterClass. And you are trying to access it using innerclass instance. That's why you are getting this error.
Also what is this + here System.out.println(+p.name); ?
Edit:
From inner class you can access outer class static members just like below:
name = "";
or
Outerclass.name = "";
change +p.name to name or OuterClass.name. + inside System.out.println will give you another compile time error.
static members are not available in object level they are available in class level. static are initialized at compile time where object is created at run time
i.name should be Outerclass.name since name is a member of Outerclass and not innerclass
in your code, i is an instance of innerclass.

The Object class is the parent class of all the classes in java by default

Why the reference type object o is not able to access variable a. It is showing error a can't be resolved or is not a field.
public class test2 {
int a;
public static void main(String args[]) {
Object o = new test2();
test2 t = new test2();
t.a = 0;
o.a = 10;
}
}
Basically, you are confused between reference type and instance (object) type.
In your program, o is the reference variable with type Object, so o will be able to access only the methods and variables from Object class.
Also, t is the reference variable with type test2, so t can access class members of test2. You can look here for more details.
In short, reference type decides which members of the class you can access.
Also, look at the below popular classes for Inheritance to understand the above concept:
public class Animal {
public String foodtype;
//other members
}
public class Dog extends Animal {
public String name;
//other members
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog();//'a' can access Anmial class members only
a.foodtype = "meat"; //ok
a.name = "puppy"; //compiler error
Dog d = new Dog();//'d' can access both Animal and Dog class members
d.foodtype = "meat"; //ok
d.name = "puppy";//ok
}
}
In Java, you can't create fields just by assigning to them. You must declare them in your code also:
public class test2 {
int a;
...
}
Even then, if you declare a variable as an Object, that is really a "test2" instance, you still won't be able to access field 'a' without casting it first.
Object o = new test2();
o.a = 5 // compile error
test2 t = (test2)o;
t.a = 5 // ok. Will compile fine
The Java compiler keeps things fairly simple, meaning that it doesn't work hard to see if "o" is really a test2 or not, it just uses the declared class to determine which fields and methods are accessible.

I've got trouble with inner and static inner class at java

Firstly, Thanks everybody that read that topic.
How can if statement become true in test class? I couldnt find any solution.I couldnt write any code in these method.I tried to send from Room class numberOfTiger to class Question's method but I didnt achieve that.
That's question about ,How can I change int variable(numberofTiger) to Cat.Tiger variable.After that if statement become true to invoke (getNumberOfTiger) method.
public class Test {
public static void main(String[] args) {
Animal an = new Animal();
Animal.Cat an1 = an.new Cat();
Animal.Cat.Tiger an2 = an1.new Tiger(3, 900, 2);
if (Animal.Question.getnumberOfTiger(an2) == 3) {
System.out.println("True");
}
}
}
public class Animal {
Cat[] c;
// inner class
class Cat {
Tiger[] t;
// inner class
class Tiger {
private int numberOfTiger;
private int averageOfTigerWeigth;
private int youngTiger;
public Tiger(int numberOfTiger, int averageOfTigerWeigth, int youngTiger) {
super();
this.numberOfTiger = numberOfTiger;
this.averageOfTigerWeigth = averageOfTigerWeigth;
this.youngTiger = youngTiger;
}
static class Question {
static int getnumberOfTiger(Cat.Tiger a) {
return 0;
}
}
}
In addition to either making Cat a static class, or using its instance,
you also need a getter for a.numberOfTiger since it is private, in Tiger class:
public getNumberOfTiger() {
return numberOfTiger;
}
Then:
return a.getNumberOfTiger();
In getNumberOfTiger() you need to return the number of tigers associated with that object. You are currently just returning 0, so it will always evaluate to false.
I see the issue. The Tiger class and the Cat class needs to be static. The reason is, a non-static inner class can call on its outer class (e.g. Cat.this.something). A non-static inner type is called like this:
instanceOfOuterClass.innerClass
whereas a static inner type is called like this:
outerClassName.innerClass
The simplest way to call on a non-static inner type is new Outer().new Inner(); The main issue with beginners in Java is that they try to do this:
new (new Outer()).Inner()
But the actual way to call it is
new Outer().new Inner()
Also, your method is always returning 0 for the count of tigers.

Make 3 classes call one another

So I'm trying to figure out how can I have 3 classes call one another.
this is the main class.
public class TestStudent {
public static void main(String[] args) {
myStudent mystudent_obj = new myStudent();
mystudent_obj.show_grades();
mystudent_obj.change_grades();
mystudent_obj.show_grades();
}
}
This is the 2nd class that's being called in the class above;
The 2nd class call another 3rd class and try to manipulate it
using two functions. Function show_grades just print out the variables in the 3rd class
and function change_grade try to change the variables in the 3rd class.
public class myStudent {
public void show_grades(){
Student student_obj = new Student();
System.out.println(student_obj.studGrade);
System.out.println(student_obj.studID);
}
public void change_grades(){
Student student_obj = new Student();
student_obj.studGrade='V';
student_obj.studID=10;
}
}
This the 3rd call, which only has two variables.
public class Student {
public int studID = 0;
public char studGrade = 'F';
}
when I run the program it runs without errors and I get an output of:
F
0
F
0
however, I can see that the function show_grades work and it does display the grades, but
the function change_grades does not change the grades:
The end results, should be something like this
F
0
V
10
because the change grade function, should have changed those variables... so what's going on?
In your myStudent class you are creating a new instance of Student in each method, meaning that each method has a local variable of class Student. When you call show_grades the second time, a new instance is created, with the default values of 0 and F.
If you create a variable and use that instead, your change grades will change the variables of the instance variable instead of a local variable in each method. This is due to scoping in programming, which you can read more about at Wikipedia.
public class myStudent {
private Student student_obj = new Student();
public void show_grades() {
System.out.println(student_obj.studGrade);
System.out.println(student_obj.studID);
}
public void change_grades(){
student_obj.studGrade='V';
student_obj.studID=10;
}
}

Categories