+ 2

How can get access to data inside private ?

How can get access to data inside private class ?

13th Feb 2018, 2:31 AM
Hossam Hassan
Hossam Hassan - avatar
2 Answers
+ 10
Private access modifier The scope of private modifier is limited to the class only. Private Data members and methods are only accessible within the class. Class and Interface cannot be declared as private. If a class has private constructor then you cannot create the object of that class from outside of the class. Let’s see an example to understand this: Private access modifier example in java This example throws compilation error because we are trying to access the private data member and method of class ABC in the class Example. The private data member and method are only accessible within the class. class ABC{ private double num = 100; private int square(int a){ return a*a; } } public class Example{ public static void main(String args[]){ ABC obj = new ABC(); System.out.println(obj.num); System.out.println(obj.square(10)); } } Output: Compile - time error
13th Feb 2018, 2:41 AM
Abhivarshini Maddala
Abhivarshini Maddala - avatar
+ 1
You can use getters and setters public class Phone { private String color; // Getter public String getColor() { return color; } // Setter public void setColor(String c) { this.color = c; } } public class Example { public static void main(String args[]) { Phone obj = new Phone(); obj.setColor("black"); System.out.println(obj.getColor()); } } // Output: black Try the code: https://code.sololearn.com/cBTUujuZEBhF
13th Feb 2018, 7:35 AM
Aleksandr