Learn Java Tutorial for Beginners (Video), Part 25: Public, Private, Protected

Discover the meaning of public, private and protected in the Java programming language. Public, private and protected are confusing for beginners, but once you understand how to use classes, they're actually quite simple.

When the video is running, click the maximize button in the lower-right-hand corner to make it full screen.



Code for this tutorial:


App.java:

 

import world.Plant;

/*
 * private --- only within same class
 * public --- from anywhere
 * protected -- same class, subclass, and same package
 * no modifier -- same package only
 */

public class App {

    public static void main(String[] args) {
        Plant plant = new Plant();
        
        System.out.println(plant.name);
        
        System.out.println(plant.ID);
        
        // Won't work --- type is private
        //System.out.println(plant.type);
        
        // size is protected; App is not in the same package as Plant.
        // Won't work
        // System.out.println(plant.size);
        
        // Won't work; App and Plant in different packages, height has package-level visibility.
        //System.out.println(plant.height);

    }

}

 

Grass.java:

 

import world.Plant;


public class Grass extends Plant {
    public Grass() {
        
        // Won't work --- Grass not in same package as plant, even though it's a subclass
        // System.out.println(this.height);
    }
}

 

Field.java:

 

package world;

public class Field {
    private Plant plant = new Plant();
    
    public Field() {
        
        // size is protected; Field is in the same package as Plant.
        System.out.println(plant.size);
    }
}

 

Oak.java:

 

package world;

public class Oak extends Plant {
    
    public Oak() {
        
        // Won't work -- type is private
        // type = "tree";
        
        // This works --- size is protected, Oak is a subclass of plant.
        this.size = "large";
        
        // No access specifier; works because Oak and Plant in same package
        this.height = 10;
    }

}

 

Plant.java:

 

package world;

class Something {
    
}

public class Plant {
    // Bad practice
    public String name;
    
    // Accepetable practice --- it's final.
    public final static int ID = 8;
    
    private String type;
    
    protected String size;
    
    int height;
    
    public Plant() {
        this.name = "Freddy";
        this.type = "plant";
        this.size = "medium";
        this.height = 8;
    }
}