Java, private access in main() [duplicate] - java

This question already has answers here:
Why am I able to call private method?
(8 answers)
Closed 3 years ago.
I am studying for the OCA Exam and came across this code:
public class Driver {
private void printColor(String color) {
color = "purple";
System.out.print(color);
}
public static void main(String[] args) {
new Driver().printColor("blue");
}
}
The question asks "What is the outcome of this piece of code". I initially thought it will be "it does not compile" because you have an object instance trying to access a private method. But, it turns out to be "purple".
Why is it "purple" and not "it does not compile"? I know the Driver instances lives in the same class it is declared in, but why it still have the privilege to access private methods?
Thank you

private means that the method is inaccessible outside the class.
Since your main method is inside the Driver class, then the private methods of Driver are accessible.

I think you missunderstood what private means. It simply means: "You can't access this method from outside the Driver-class." And since you are inside the class, the compiler allows the access.

Related

How to access a static field from a class passed as a parameter to a function in Java? [duplicate]

This question already has answers here:
Accesing static variable from another class in java
(2 answers)
Closed 2 years ago.
public class Parameter {
public static int my_static_int;
}
public class Test {
public void foo (Class<Parameter> argument) {
argument.my_static_int = 1;
}
When I type this code, Eclipse gives me an error when I try to access my_static_int in the function foo, saying my_static_int cannot be resolved or is not a field. Could someone tell me what I'm doing wrong?
The static modifier in Java is directly related to the class. If the field is static, it means that it belongs to the class. Based on this, you can access a static method or field using the class name.
In your case, you can access the field directly:
Parameter.my_static_int

How does Out variable which is defined static and assigned null in System class can access non-static methods of PrintStream class. [duplicate]

This question already has answers here:
System.out is declared as static final and initialized with null? [duplicate]
(2 answers)
Closed 5 years ago.
As to access the methods of PrintStram class an object must be created, so how the out variable is able to access those methods when it is assigned null.
public final static PrintStream out = null;
This is the declaration in System class.
I tried to write the similar code but then it gives NullPointerException. My code is given below.
class First{
public void display(){
System.out.println("Hello");
}
}
class Second{
public final static First s1=null;
}
public class Third{
public static void main(String[] args) {
Second.s1.display();
}
}
To make this code run i will have to make either display method static or define s1 as-
public final static First s1=new First();
The field isn't null at runtime. It's assigned the relevant stream stdout or something else if it has been redirected. The mechanism is internal to the JVM, so the code isn't readily visible in the JDK sources. You can use System.setOut() to modify the field, which again uses internal mechanisms as the field is final and normally wouldn't be assignable.
You may have missed the System.initializeSystemClass() which according to the documentation is called after the class initialization. It initialize the in, out and err stream. It use native methods to do that, so it doesn't have to respect the final modifiers.

Can you access private data fields without setter methods in Java? [duplicate]

This question already has answers here:
What is the difference between public, protected, package-private and private in Java?
(30 answers)
Closed 6 years ago.
In the top stackoverflow answer to this question (Why are instance variables in Java always private?), someone said if you have the following class with a private string,
class Address {
private String phone;
}
then you can't modify the private string using the following code, but I tried it and it works.
// main method
Address a = new Address();
a.phone="001-555-12345";
He said you had to use a setter method, but I did it without using one.
I think I misinterpreted his answer, but I'm not sure how. I would appreciate any insight, thanks.
Your main method must be held within your Address class for this to work, since private fields are accessable only within the class that they are declared in. Try changing your code so that the main method is located elsewhere (as is usually the case) and it will no longer work.
e.g., this works:
class Address {
private String phone;
public static void main(String[] args) {
Address a = new Address();
a.phone="001-555-12345"; // this works fine -- it's within Address
}
}
but keep the above code and try this one:
class TestAddress {
public static void main(String[] args) {
Address a = new Address();
a.phone="001-555-12345"; // won't compile since it's not within Address class
}
}

Confused with why private variable can be accessed? [duplicate]

This question already has answers here:
Why can I access a private variable from main method?
(7 answers)
Closed 8 years ago.
I recently see a question that what is the execution result of this code below.
public class Sandys {
private int court;
public static void main(String argv[]){
Sandys s = new Sandys(99);
System.out.println(s.court);
}
Sandys(int ballcount){
court = ballcount;
}
}
I think it can't be executed because in main i try to access a private variable.
However, this code can be perfectly executed, and the result is 99. So I am confused, why the private variable can be accessed in this code? Though the main is in Sandys class, however i create a new Sandys. Can I still access the private variable of the new Sandys object in main?
You can access private members from inside the same class, even in static methods.
main() is a special method because it is used as a starting point for java application. However, it is still a normal static method and it follows all access restrictions of static methods. Is this main() a class method? Yes, it is. Hence, it can access private members of the same class.
Consider this: if there was no access to private fields factory methods would have to be written differently.
class A {
private int a=0;
private int b=0;
private A() {}
//getters
public static A getNewInstance(int a, int b) {
A a = new A();
a.a = a;
a.b = b;
return A;
}
It does make sense, doesn't it?
You can access ALL private, protected, public and not modifier variables inside class, but you can not access private variable from another class.
P.S. It is truth also for C#, C++ and many other programming languages.
A class is defined to some particular job and in that way it may use some variables that it don't want others to access it("others" means outsider classes) and some you want other classes to access it.It all depends on your requirement.
"Private instance variables are defined to be used in only with in the class".and since in your code you are trying to access the private instance variable inside the class itself then it is perfectly legal.
Note: A static method cannot access the instance variables if u want specify the instance i mean create the instance(object) inside of the static method and access it through the created reference.

non-static variable v_var cannot be referenced from a static context [duplicate]

This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 8 years ago.
I have a class called "setup" that has a method that returns a string
public class Setup{
public String getPW(){ return "pAssWord";}
}
I imported "Setup", tried to assign it to private static String, and then the system throws this error.
public class Something {
private Setup v_var= new Setup();
private static String password = v_var.getPW();
}
It accepts the hardcoded string, but not method called String.
Can someone explain me a logic behind this?
var_v is an instance variable. Each instance of your class would have a different value for this var. password is a static member, and is the same for all instances of your class. That's why you can't assign to it a value that is specific to an instance.

Categories