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
}
}
Related
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.
This question already has answers here:
What is the meaning of "this" in Java?
(22 answers)
When should I use "this" in a class?
(17 answers)
Closed 4 years ago.
I have a question.
Please don't mark it as duplicate, Go through the question once. I can't find an answer to this specific situation/condition, If you feel it has a specific answer then only mark duplicate. Marking it duplicate makes my question remain a question without an answer.
What's the difference between calling a method with/without this as a keyword. Which one is better?
The question specifically applies for a single class.
Please have a look at the sample code below to fully understand the question.
public class ThisSample {
public static void main(String[] args) {
ThisSample sample = new ThisSample();
sample.methodOne();
}
public void methodOne() {
System.out.println("Method 1 called");
this.methodTwo(); //Line 1
methodTwo(); // Line 2
}
public void methodTwo() {
System.out.println("Method 2 called");
}
}
What difference (Advantage/disadvantage/implication) does the 2 lines (Line 1 & Line 2) in the code make?
Thanks & Regards,
Yadvendra
'This' task is to differentiate object property from method parameter. In presented code usage of this does nothing. However the most common use is like in this example:
public class Service {
private ServiceA serviceA;
private ServiceB serviceB;
// Here 'this' is used to make sure that class instance
// properties are filled with constructor parameters
public Service(ServiceA serviceA, ServiceB serviceB) {
this.serviceA = serviceA;
this.serviceB = serviceB;
}
}
this is used to specify that you're talking about the method methodTwo from the current instance of the class ThisSample.
If you'd have another class called AnotherSample:
public class AnotherSample{
public static void methodThree()
{
// some code
}
}
You could use the method methodThree by calling it as follows AnotherSample.methodThree();.
In summary: this just specifies that you're using the instance of the class you're currently coding in.
In the example, you have given, the difference is nothing. Let me modify your code a bit:
public class ThisSample {
int variable;
public static void main(String[] args) {
ThisSample sample = new ThisSample();
sample.methodOne(3);
sample.methodTwo(5);
}
public void methodOne(int variable) {
this.variable = variable;
System.out.println("variable is: " + this.variable);
}
public void methodTwo(int variable) {
variable = variable;
System.out.println("variable is: " + this.variable);
}
}
Here, for method 2, you must use this.variable to set the value in the instance variable. Otherwise, both method will print 3 here. The second method is also printing three because you set 3 in method one.
Now in method 2, in
variable = variable
line, both variable are paramater of mathod 2. But when you are writing,
this.variable = variable;
you are telling, left one is instance variable of this object and right part is assigned to instance variable of this object.
Edit:
If you want to know "which is more preferred", then see this link too. Here using this is said "redundant". Link is: https://softwareengineering.stackexchange.com/a/113434/162116
Here, it is also said that, I should refactor the code if I actually need this to deduce the instance variable.
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.
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.
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.