how private static instance variable is accessed in main() - java

public class test
{
private static int a;
public static void main(string[] args)
{
modify(a);
system.out.print(a);
}
public static void modify(int a)
{
a++;
}
}
i want to know how a private static variable is accessed directly in main() method.
although static variables can be accessed directly from static methods but the variable is private and method is main().. pls explain

Yes, it is static but since it is located in the same class as main method, it can be accessed by the static methods in the class (including main)... and actually also by normal methods in the same class

It doesn't bother you that modif() can access the attribute a ? Then it's the exact same thing with the main().
The only special thing about main() is the fact that this method is used as an entry point of your application. This particularity doesn't interfer with the fact that main() is static.
By the way, your modif() method doesn't really access the static a field because it's shadowed by the parameter a.
Another thing, a++ won't do anything because you're just modifying the value of the parameter a inside a method; int is a primitive and is passed by value, so your code won't change the value of a outside of the method scope.
I think you wanted something like this :
public class test{
private static int a;
public static void main(string[] args){
modify(); //<--- No parameters needed here !
system.out.print(a);
}
public static void modify(){ //<--- No parameters needed here !
a++;
}
}

If you declare a member variable as private, this means it can only be accessed from methods in the same class. Your main() method is actually a static method in the same class, so it can access any private variables.

Since main is in the same class you can access the private variable.

A private member variable is visible to any method of that class, static or not. There are restrictions on what static methods can do but those are separate from the visibility rules.

but
public class test
{
private int a;
public static void main(string[] args)
{
system.out.print(a);
}
}
you can't access a instance variable 'a' directly in main()... it will show error bcoz it is private...... but how it accesses private static...

Related

Is it possible to access a private static variable and method?

We can access a static property of a class by writing className.propertyName, but if the property (method/variable) is private then is it possible to access that property?
For example,
class A{
static int a = 50;
}
public class HelloWorld{
public static void main(String []args){
System.out.print("A.a = ");
A obj = new A();
System.out.println(A.a);
}
}
This will print A.a = 50
But if I change static int a = 50; to private static int a = 50; then can I access that variable any how?
The private keyword means that it'll only be visible within the class. So in your example it means that you cannot access it like A.a. What you can do though is to create a public method that returns a.
private static int a = 5;
public static int getA () {
return a;
}
You can then statically call this method and retrieve the private static field.
// ...
System.out.println(A.getA());
Usually private static fields are rarely used though.
One more thing I'd like to add is the general use of static here.
As you actually create an instance of the class A the static modifier is redundant.
You cannot access the private in outside class or outside the package .Because private making them only accessible within the declared class.if you want to access the variables in the class means public,default and protected are only accessible .outside the package
means default is not possible only public and protected is possible ,protected also have different package and non sub class means not possible only sub class is possible(need to extend the class).public only accessible for all inside and outside the packages.

Can we access the static member of a class without initializing obects?

public class Test{
static Another a;// without initializing i can able to access static member of Another class
public static void main(String[] args){
System.out.println(a.i);
}
}
class Another{
public static int i=20;
}
Here I can able to the access the static member of class Another without initializing the object and the system is displaying the output as 20.
public class Test{
public static void main(String[] args){
Another a;// but when i declare this inside the main method system is throwing error
System.out.println(a.i);
}
}
class Another{
public static int i=20;
}
Test.java:5: error: variable a might not have been initialized
System.out.println(a.i);
^
But when i move the declaration inside main block system throws an error. why is that?
public static void main(String[] args){
Another i
System.out.println(a.i);
}
this can be replaced with
public static void main(String[] args){
System.out.println(Another.i);
}
You are getting error not because the static variable i but **because of local method variable Another a is not initialized ** , Since you have not initialized a, the local variable inside a function must be intialized befor reading its value.
You should access the static variable i with Another.i, not a.i.
a.i is valid syntax if a has a value, but it's confusing (since anyone who reads you code may falsely assume i is an instance variable). And if a is not initialized when you access it, the compiler doesn't allow it.
The difference between the two snippets is that here (when a is a static variable):
static Another a;
a has a default value of null.
While here (when a is a local variable):
Another a;
it has no default value.

Yet another non static variable cannot be referenced issue

I've read this, and also this and I guess I'm getting the theroical point af static and non static content but I'm unable to apply it to the following case (which is supposed to work) May be so, so, so basic but... humans.
public class MyClass {
private String varA ;
private int varB;
public MyClass(String var, int var) throws SocketException {
//stuff to work with
}
private void methodA() {
//more stuff....
}
public static void main(String args[]) throws IOException {
//How to instatiate MyClass(varA,varC)?
}
}
So, how it's supposed to be instatiated MyClass from main if MyClass is not static?
How to instatiate MyClass(varA,varC) ?
public static void main(String args[]) throws IOException {
//local variables
String varA = "A";
int varC = 10;
//Use the constructor of the class to create an object
MyClass myClassObj = new MyClass(varA, varC);
}
You always need to use the constructors provided by the class to instantiate a class. You don't have the default (no argument) constructor in your class, so you need to pass the constructor arguments as shown above to instantiate the class.
You can look here.
In your MyClass class instance variables varA, varB are created/maintained for each object(instance) separately.
Just to add, if there are any static variables present in a class, they will be maintained only per class (not for each object).
I hope this answer will be helpful for you to understand why main method is static in non-static class
Why is the Java main method static?
Also, in code :
MyClass myClass = new MyClass(varA, varC);
Create new instance of you class using public constructor with your own parameters list.
Agree with JavaGuy.
Just for your clarity's sake, main method is made static so that it can be called from JVM without instantiation of the class. Hence to access any non static member of the class you need to have an instance of the class as mentioned by above solution by JavaGuy.

Can static method access non-static instance variable?

So my understanding was that you can't use static method to access non-static variables, but I came across following code.
class Laptop {
String memory = "1GB";
}
class Workshop {
public static void main(String args[]) {
Laptop life = new Laptop();
repair(life);
System.out.println(life.memory);
}
public static void repair(Laptop laptop) {
laptop.memory = "2GB";
}
}
Which compiles without errors.
So isn't
public static void repair(Laptop laptop) {
laptop.memory = "2GB";
}
accessing String memory defined in class Laptop, which is non-static instance variable?
Since the code compiles without any error, I'm assuming I'm not understanding something here. Can someone please tell me what I'm not understanding?
A static method can access non-static methods and fields of any instance it knows of. However, it cannot access anything non-static if it doesn't know which instance to operate on.
I think you're mistaking by examples like this that don't work:
class Test {
int x;
public static doSthStatically() {
x = 0; //doesn't work!
}
}
Here the static method doesn't know which instance of Test it should access. In contrast, if it were a non-static method it would know that x refers to this.x (the this is implicit here) but this doesn't exist in a static context.
If, however, you provide access to an instance even a static method can access x.
Example:
class Test {
int x;
static Test globalInstance = new Test();
public static doSthStatically( Test paramInstance ) {
paramInstance.x = 0; //a specific instance to Test is passed as a parameter
globalInstance.x = 0; //globalInstance is a static reference to a specific instance of Test
Test localInstance = new Test();
localInstance.x = 0; //a specific local instance is used
}
}
You can access only with object reference.
Instance variables defined at class level, have to be qualified with object name if you are using in a static context. But it does not not mean that you cannot access at all.
Static methods cannot modify their value.
You can get their current value by accessing them with the reference of current class.
Yes, a non-static method can access a static variable or call a static method in Java. There is no problem with that because of static members
i.e. both static variable and static methods belongs to a class and can be called from anywhere, depending upon their access modifier.
For example, if a static variable is private then it can only be accessed from the class itself, but you can access a public static variable from anywhere.
Similarly, a private static method can be called from a non-static method of the same class but a public static method e.g. main() can be called from anywhere
try this code
public static void repair() {
Laptop laptop =new Laptop();
laptop.memory="2GB";
}

why it is possible to get access to private field in static method if you pass object as parameter

For example I've got simple class
class Simple {
private int i = 6;
private static void method(Simple obj) {
System.out.println("Value i: " + obj.i);
}
public void method() {
method(this);
}
public static void main(String[] args) {
new Simple().method();
}
}
Why I can get access to i in static method?
private members can be accessible with in the class. Your static method belongs to the same class. Hence you can access.
Modifier Class Package Subclass World
---------------------------------------------
private **Y** N N N
Update: To avoid the confusion, move the static method to other class and try once.
Don't get confused with static and private/public/[default]. Those are two separate things. A static function can access private non-static field because it is part of the class. And thats whats private does, only restricting access to the class level, without any distinction being made between static or not.
If it's the staticness that's bothering you, obj is a proper "not static" object, which us why it has an accessible non-static field. The method being static is irrelevant.
you are accessing instance of object not directly class variable. when you use direly "i" without reference to object its not allowed.
Private variable visibility is by default in with in class access .
public class Simple {
private int i = 6;
private static void method(Simple obj) {
System.out.println("Value i: " + i); //compile Error ::Cannot make a static reference to the non-static field i
}
public void method() {
method(this);
}
public static void main(String[] args) {
new Simple().method();
}
}

Categories

Resources