Why isn't this code working
public class BB
{
private class A
{
private int x;
}
public static void main(String[] args)
{
A a = new A();
a.x = 100;
System.out.println(a.x);
}
}
while this code is working?
public class BB
{
private class A
{
private int x;
}
static int y = 3;
public static void main(String[] args)
{
BB b = new BB();
b.compile();
System.out.println("y = "+ y);
}
public void compile()
{
A a = new A();
a.x = 100;
System.out.println(a.x);
System.out.println("y = "+ y);
}
}
In first code, When I am trying to refer to instance variable 'x' of inner class 'A' by an object of inner class 'a', I am getting an error saying that I'm using inner class in static context.
There is no error while doing the same in some other method.
Your error has nothing to do with field access. Compilation fails for this line:
A a = new A();
Reason: you cannot instantiate an inner class without an enclosing instance, which is exactly what that line of code tries to do. You could write instead
A a = (new BB()).new A();
which would provide an enclosing instance inline. Then you will be able to access the private field as well.
Alternatively, just make the A class static, which means it does not have an enclosing instance.
private class A is like an instance member and we can not use instance member inside static method without making its object. So first we need to object of outer class than we can use instance inner class. And below code is working fine.
class BB
{
private class A
{
private int x;
}
public static void main(String[] args)
{
BB bb = new BB();
BB.A a = bb.new A();
a.x = 100;
System.out.println(a.x);
}
}
Related
What did I do wrong here? Need to print -1 and 100 but I keep getting this error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
No enclosing instance of type Main is accessible. Must qualify the allocation with an enclosing instance of type Main (e.g. x.new A() where x is an instance of Main).
at Main.main(Main.java:3)
public static void main(String[] args) {
MyClass a = new MyClass();
MyClass b = new MyClass(100);
System.out.println(a.getValue()); // -1
System.out.println(b.getValue()); // 100
}
public class MyClass {
private int value;
// Constructors
public MyClass() {
value = -1;
}
public MyClass(int x) {
value = x;
}
public int getValue() {
return value;
}
}
}
Your problem is that your main method has no class. Here you have an example:
public class Main {
public static void main(String[] args) {
MyClass a = new MyClass();
MyClass b = new MyClass(100);
System.out.println(a.getValue()); // -1
System.out.println(b.getValue()); // 100
}
}
class MyClass {
private int value;
// Constructors
public MyClass() {
value = -1;
}
public MyClass(int x) {
value = x;
}
public int getValue() {
return value;
}
}
You can also create some inner classes, as explained here: https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
But, if you are starting as a programmer, I don't recommend you to create neither inner nor outer classes, and rather create a new class. Something like:
org.demo.myclasses.Main ==> This is your Main class with your main method.
org.demo.myclasses.MyClass ==> Another different file for your new class.
Here's another question made by another user with more info about it: Java inner class and static nested class
I am clear that accessing a private field in Java could be easily achieved by using Reflection. As is shown in posts as How to read the value of a private field from a different class in Java? and there are many.
To achieve that , the critical move is to set accessibility.
Field f = obj.getClass().getDeclaredField("aaa");
f.setAccessible(true);
But in my case, the situation is like:
class A{
private B b;
class B{
private String value;
}
}
and I want to get value of a.b.value in another class. When I was trying, I intended to do it as
A obj = createInstanceA();
Field f = obj.getClass().getDeclaredField("b");
f.setAccessible(true);
A.B b = f.get(obj);
Field f2 = b.getClass().getDeclaredField("value");
f2.setAccessible(true);
String value = f2.get(b);
Which doesn't work out because B could not be declared out of A.
Do I have other options if Class A can not be modified?
You have do like this,
public class A {
private B b = new B();
class B {
private String value = "String";
}
}
public class ClassB {
public static void main(String args[]) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{
A obj = new A();
Field f = obj.getClass().getDeclaredField("b");
f.setAccessible(true);
A.B b = (B) f.get(obj);
Field f2 = b.getClass().getDeclaredField("value");
f2.setAccessible(true);
String value = (String) f2.get(b);
System.out.println(value);
}
}
What you are missing is to setAccessible(true) to inner class field.
As a first, in your example field b is null. Is this correct?
So, you try to get class of null.
As a second, in your example you use inner classes and there is a specific langugage mechanizm. You can create instance of class B only by some instance of class A. And all instances of class B has access to private field of it's parrent (class A). As in this example.
class OuterClass
{
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;
// private member
private int outer_private = 30;
// inner class
class InnerClass
{
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);
// can also access non-static member of outer class
System.out.println("outer_y = " + outer_y);
// can also access private member of outer class
System.out.println("outer_private = " + outer_private);
}
}
}
// Driver class
public class InnerClassDemo
{
public static void main(String[] args)
{
// accessing an inner class
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
innerObject.display();
}
}
May be inner classes can solves your problem? (You can read abou it here https://www.geeksforgeeks.org/nested-classes-java/)
Then reflecsoin is not needed.
public class MyClass {
int x=9;
public static void main(String args[]) {
MyClass myClass = new MyClass();
myClass.test();
}
public void test(){
int x=10;
class InnerClass{
int x = 11;
void print(){
int x = 12;
System.out.println(x);
System.out.println(this.x);
System.out.println(MyClass.this.x);
System.out.println("MyClass => test() => x :" + "?");
}
}
InnerClass innerClass = new InnerClass();
innerClass.print();
}
}
How to call MyClass test() method local variable x inside the InnerClass print() method. What i can write in place of ? in last System.out.println() method in order to get the value of test() x.
Unfortunately in Java you can't.
The only way to access the x in MyClass::test would be to rename both variables in your inner class and in your inner class method into something else.
There is no need though to rename the outer class field x as InnerClass::print would consider the variable in the most-inner scope.
Although this snippet is for demonstration purposes, better practice would have you have different and more significant names for each variable.
That works fine for me:
public class Outerclass {
public static void main(String args[]) {
Outerclass outer = new Outerclass();
outer.outerMethod();
}
// method of the outer class
void outerMethod() {
int num = 23;
// method-local inner class
class MethodInnerClass {
public void print() {
System.out.println("This is method inner class "+num);
}
}
// Accessing the inner class
MethodInnerClass inner = new MethodInnerClass();
inner.print();
}
}
To print outer class variable use
MyClass.this.x
If I make for example one project. Inside with two class. For example: X and Y. I make them what I want, and I want to make a main method in Y. Only system.out.printlf the values in X and Y. But it writes that I need to make them static if I want to run this. I tried to make a new file with only the main class and inside the X Y values but it showed an error. What I missed?
you have missed object creation. Try X x = new X(); in your Y file. I would recommend to read some tutorials on Java, starting from here.
The main method is declared static
public static void main(String[] args) {}
Inside of main, it can only access static variables that exist in the enclosing class. You will see this for example with this bit of code:
public class X {
private int i = 5;
public static void main(String[] args) {
System.out.println(i);
}
}
To make the above work you need to declare i as static:
public class X {
private static int i = 5;
public static void main(String[] args) {
System.out.println(i);
}
}
A better way would be to do this:
public class X {
private int i = 5;
public X() {
System.out.println(i);
}
public static void main(String[] args) {
new X();
}
}
Static methods can only access static methods and other variables declared as static.
This article may also help you to understand what is going on here.
I'm guessing that's because everything happens inside the main method which is indeed static right? e.g.
public class C {
int X;
int Y; //or whatever other type
..
public static void main(String args[]) {
System.out.print( X ); //this won't work!
}
}
instead use this aprroach:
public class C {
int X;
int Y; //or whatever other type
..
public static void main(String args[]) {
C inst = new C();
System.out.print( c.X ); //this will work!
}
}
The main method is static and can only access static fields from the class. non static fields belong to an instance/object which you'd have to create:
public class X {
static int a = 0;
int b = 0;
public static void main(String[] args) {
System.out.println(a); // OK -> accesses static field
System.out.println(b); // compile error -> accesses instance field
X x = new X();
System.out.println(x.b); // OK -> accesses b on instance of X
}
}
how to initialize a private static member of a class in java.
trying the following:
public class A {
private static B b = null;
public A() {
if (b == null)
b = new B();
}
void f1() {
b.func();
}
}
but on creating a second object of the class A and then calling f1(), i get a null pointer exception.
The preferred ways to initialize static members are either (as mentioned before)
private static final B a = new B(); // consider making it final too
or for more complex initialization code you could use a static initializer block:
private static final B a;
static {
a = new B();
}
Your code should work. Are you sure you are posting your exact code?
You could also initialize it more directly :
public class A {
private static B b = new B();
A() {
}
void f1() {
b.func();
}
}