Packages and Access modifiers

Packages

     Encapsulation in java is a process of wrapping code and data together into a single unit. The date in a class is hidden from other classes, so it is also known as Data-hiding.


Advantage of Java Package

  1. Java package is used to categorize the classes and interfaces so that they can be easily maintained.
  2. Java package provides access protection.
  3. Java package removes naming collision.


Access Modifiers
        The access modifiers in java specifies the accessibility or scope of a field, method, constructor, or class.. We can change the access level of fields, constructors, methods and class by applying the access modifier on it.

There are four types of java access modifiers:   

Private The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
Default The access level of a default modifier is only within the package. It cannot be accessed from outside the package if you do not specify any access level, t will be the default.
Protected The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.
Public The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.


Practice Set

1. Create these classes Calculator, ScCalculator and hybridCalculator and group them into a package.
package calc;

class Calculator{
    public void calculator(int a, int b){
        System.out.println("i am main method"+ a+ b);
    }
}

class ScCalculator{
    public void calculator(int a, int b){
        System.out.println("i am main method"+ Math.sin(a+ b));
    }
}

class Hycalculator{
    public void calculator(int a, int b){
        System.out.println("i am main method"+ Math.sin( a+ b));
    }
}

public class Problem1{
    public static void main(String args[]){
        System.out.println("i am main method");
    }
}
Run Command
PS G:\oops\practice set> javac -d . Problem1.java
PS G:\oops\practice set> java calc/Problem1
i am main method
PS G:\oops\practice set>

2. Use a built-in package in java to write a class which display a message (by using system.out.prinln() ) after taking input from the user.