Encapsulation

Description:

Encapsulation: a technique of making the fields in a class private and providing access to it through public methods. It hides the fields and therefore is also referred to as data hiding. It also hides the implementation details which gives maintainability, flexibility and extensibility to our code.

Static: denotes that a member variable, or method, can be accessed without requiring an instantiation of the class to which it belongs.

When to useEncapsulation is to be used when you want to set varing degrees of security ond classe/objects attributes or methods

Modifier

Class

Package

Subclass

World

public

Y

Y

Y

Y

protected

Y

Y

Y

N

No modifier

Y

Y

N

N

private

Y

N

N

N

Exmaple:

Class:

public class Person {
    public static String name = "Mac";
    static int age = 24;
    protected static String secret = "Don't like south park";
    private static String SSN = "000-11-2222";
    
    public static String displaySSN(){
        return SSN;
    }
}

SubClass:

public class PersonFriend extends Person {
    public static String gossip(){
        return secret;
    }
}

Main class:

public class Main {

    public static void main(String[] args) {
        
        new Person();
        new PersonFriend();
        
        System.out.println("This is public information: " +Person.name);
        System.out.println("This is protected information: " + PersonFriend.gossip());
        System.out.println("This is unmodified information: " +Person.age);
        System.out.println("This is private information: " +Person.displaySSN());
    }
}

Results:

This is public information: Mac
This is protected information: Don't like south park
This is unmodified information: 24
This is private information: 000-11-2222

 

Leave a Reply