Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Private:
- Variables, Methods:
- * Can only be accessed by members of the class they belong to:
- class TestClass{
- private int number = 4;
- public int getNumber(){
- return number;
- }
- public void addOneToNumber(){
- number = number + 1;
- }
- }
- * Can not be accessed from other classes:
- class SecondTestClass{
- public void tryToAccessPrivate(){
- TestClass test = new TestClass();
- test.number = 1000; //Will error.
- }
- }
- Class:
- * Are not stand-alone classes.
- * Are classes inside other classes.
- * Can only be accessed by the class they are in to.
- Public:
- Variables, Methods:
- * Can be accessed from all other classes
- * Public variables are discouraged as they ruin the concept of Encapsulation
- * Variables are made private in classes typically, and public methods called 'getters' and 'setters' are created with the purpose of 'interfacing' the variables. This is called Encapsulation.
- * Methods are declared public if and only if there is a reason why they need to be accessible from other classes. Do not make all methods public.
- Comparison:
- Public permits access to variables, methods, and classes from other classes regardless of their package and/or other properties whereas private declares the method/variable or class only accessible from the class surrounding it and other members of this class.
- Use of public for variables is discouraged as it does not follow the fundamental OOP concept of encapsulation.
- Static:
- Whatever is marked as 'static' belongs to the class and not to an object, and will remain the same for all objects
- In further detail if you have a static variable in a class, it will be the same for all objects of this class!
- For example:
- class FirstClass{
- public static int staticNumber = 110;
- public int nonStaticNumber = 550;
- public static void staticMethodPrintHello(){
- System.out.println("Hello");
- }
- public void nonStaticMethodPrintHey(){
- System.out.println("Hey");
- }
- }
- class SecondClass{
- public static void main(String[] args){
- System.out.println(FirstClass.staticNumber); //access 'number' from FirstClass which is static
- FirstClass instance = new FirstClass();
- System.out.println(instance.nonStaticNumber);//accessing non static variable requires an instance.
- // Methods:
- FirstClass.staticMethodPrintHello();//using a static method requires no Object.
- FirstClass instanc = new FirstClass();
- instanc.nonStaticMethodPrintHey(); //using a non static method requires an Object (instanc)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement