-2

If constructors are implicitly invoked functions at the time of object creation then we should declare variable in constructor , but it is giving an error.

class A{
    
    public A(){
        int a =5;
    }
}


public class assignment2 {
    public static void main(String[] args) {
       A obj = new A();
       System.out.println(obj.a);
    }
}

Error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
        a cannot be resolved or is not a field

        at ass2.main(ass2.java:14)
atliqui17
  • 78
  • 3

4 Answers4

1

Variable int a is not a field but, as you said, variable and immediately after the constructor will finish it's not accessible anymore and definitely not by obj.a

You should move it's definition outside the constructor (so basically create field a) if you wish to use it this way

What is the difference between field, variable, attribute, and property in Java POJOs?

m.antkowicz
  • 13,268
  • 18
  • 37
0
class A{
    public int a;

    public A(){
        this.a =5;
    }
}

For more information on declaring constructors refer: https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

the Hutt
  • 16,980
  • 2
  • 14
  • 44
0

It'a just a member variables, which doesn't belong to obj, u should declare a as local variables:

public class Test{
    public int a = 5;
    public Test() {
        
    }
}

0

Declaring variables in constructor int a (in your case) will still work locally in the constructor. the a variable will be destroyed as the constructor finish his work. so you can't access to this Variable from another place.

To create a field and make your code work. take the declaration outside of the constructor. then you can initialize it in the constructor..

lasseg
  • 11
  • 5