Access Modifiers and Inheritance

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn access modifiers and inheritance. With different modifiers, access levels are different. Inheritance in Java is like biological inheritance in that children can keep parent's features and behave differently in some way.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/inner_classes("`Inner Classes`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_attributes("`Class Attributes`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/constructors("`Constructors`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/encapsulation("`Encapsulation`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/inheritance("`Inheritance`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-178543{{"`Access Modifiers and Inheritance`"}} java/inner_classes -.-> lab-178543{{"`Access Modifiers and Inheritance`"}} java/classes_objects -.-> lab-178543{{"`Access Modifiers and Inheritance`"}} java/class_attributes -.-> lab-178543{{"`Access Modifiers and Inheritance`"}} java/class_methods -.-> lab-178543{{"`Access Modifiers and Inheritance`"}} java/constructors -.-> lab-178543{{"`Access Modifiers and Inheritance`"}} java/encapsulation -.-> lab-178543{{"`Access Modifiers and Inheritance`"}} java/inheritance -.-> lab-178543{{"`Access Modifiers and Inheritance`"}} java/modifiers -.-> lab-178543{{"`Access Modifiers and Inheritance`"}} java/oop -.-> lab-178543{{"`Access Modifiers and Inheritance`"}} java/identifier -.-> lab-178543{{"`Access Modifiers and Inheritance`"}} java/arrays -.-> lab-178543{{"`Access Modifiers and Inheritance`"}} java/comments -.-> lab-178543{{"`Access Modifiers and Inheritance`"}} java/data_types -.-> lab-178543{{"`Access Modifiers and Inheritance`"}} java/operators -.-> lab-178543{{"`Access Modifiers and Inheritance`"}} java/output -.-> lab-178543{{"`Access Modifiers and Inheritance`"}} java/strings -.-> lab-178543{{"`Access Modifiers and Inheritance`"}} java/variables -.-> lab-178543{{"`Access Modifiers and Inheritance`"}} java/system_methods -.-> lab-178543{{"`Access Modifiers and Inheritance`"}} end

Access Modifiers

For now, we have already written some code. In the previous lab, we have written a class. There are some modifiers like public and private. So, what do these words mean?

Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:

  • default: Visible to the package, the default one. No modifiers are needed.
  • private: Visible only to the defining class.
  • public: Visible to the Java Universe (all the types). You can access them anywhere.
  • protected: Visible to the package and all subclasses (even those in other packages).

Java provides a number of non-access modifiers to achieve many other ways of fine tuning of behavior:

  • static: This modifier is used to create variables or methods that will exist independently of any instances of class. Only one copy of the static variable exists for the class regardless of the number of instances created.
  • final: A final variable can be explicitly initialized only once. A final method cannot be overridden by any subclasses. A class is declared as final to prevent the class from being subclassed.
  • abstract: An abstract class can never be instantiated. An abstract method is a method declared without any implementation.
  • synchronized/volatile: The synchronized and volatile modifiers are used in connection with threads.

Example:

Write the following code in the /home/labex/project/modifierTest.java file:

public class modifierTest {
    // static variables are initialized when class is loaded.
    public static int i = 10;
    public static final int NUM = 5;
    // non-static variables are initialized when object is created.
    public int j = 1;

    /*
     * static code block here, this will execute when the class is loaded
     * creating new object will not execute the block again, run only once.
    */
    static{
        System.out.println("this is a class static block.");
    }
    public static void main(String[] args)
    {
        System.out.println("this is in main method");

        // you can access i and change it
        modifierTest.i = 20;  //the same with obj.i = 20
        System.out.println("Class variable i = " + modifierTest.i);
        // you can access NUM, but can't change it
        // HelloWorld.NUM = 10;     this will cause an error, NUM is final, it's immutable
        System.out.println("Class variable NUM = " + modifierTest.NUM);

        // create new object
        modifierTest obj = new modifierTest();
        // we can use both class and object to access static methods and static properties
        obj.staticMethod();  // the same with modifierTest.staticMethod()
        // you can't access j like this: modifierTest.j
        System.out.println("Object variable j = " + obj.j);
    }
    // the constructor, only new object being created will call this.
    public modifierTest(){
        System.out.println("this is in object's constructor.");
    }
    public static void staticMethod(){
        System.out.println("this is a static method");
    }
}

Output:

Run the modifierTest.java file using the following commands:

javac /home/labex/project/modifierTest.java
java modifierTest

See the output:

this is a class static block.
this is in main method
Class variable i = 20
Class variable NUM = 5
this is in object's constructor.
this is a static method
Object variable j = 1

Inheritance

In many cases, we have written a class. And, then we need to write a new class just to modify a little of previous class code, and they have some relation in logic. We can use inheritance here. We use the keyword extends to implement inheritance. Subclasses get all the accessible properties and methods of the superclass by inheritance, and subclasses can also have their own special ones. In subclasses, we can access the ones that are declared in the superclass as public or protected, but the private ones we can't access directly. See an example: The inheritance structure is showed as the picture. You can implement multilevel inheritance (horizontal) or hierarchical inheritance (vertical):

Example:

Write the following code in the /home/labex/project/inheritanceTest.java file:

class Animal{
    // what kind of animal i am.
    private String species;
    private int age = 8;

    public Animal(){
        System.out.println("Animal's constructor");
    }
    public void grow(){
        // In this class, we can access the private properties directly.
        System.out.println("I'm "+ this.age + " years old, " +"I grow up.");
    }
}
class Dog extends Animal{
    private String color;
    // In this class, we can't access superclass private attributes, but grow() is ok.
    public Dog(){
        System.out.println("Dog's constructor");
    }
    public void run(){
        this.grow();
        System.out.println("I'm dog, I can run.");
    }
}
class Bird extends Animal{
    private double weight;

    public Bird(){
        // if explicitly invoke superclass constructor, it must be at the first line here.
        // super();
        System.out.println("Bird's constructor");
    }
    public void fly(){
        this.grow();
        System.out.println("I'm bird, I can fly.");
    }
}
public class inheritanceTest{
    public static void main(String[] args){
        Dog dog = new Dog();
        dog.run();

        Bird bird = new Bird();
        bird.fly();
    }
}

Output:

Run the inheritanceTest.java file using the following commands:

javac /home/labex/project/inheritanceTest.java
java inheritanceTest

See the output:

Animal's constructor
Dog's constructor
I'm 8 years old, I grow up.
I'm dog, I can run.
Animal's constructor
Bird's constructor
I'm 8 years old, I grow up.
I'm bird, I can fly.

When you see this output, you may get confused. Don't worry; we'll explain why. When we create an object of a subclass using new, it by default first invokes the default constructor of superclass from the inheritance tree structure "top down" and lastly executes its own constructor. The superclass constructor can be called explicitly using the super keyword, but it must be the first statement in a constructor it is is there. The super keyword refers to the superclass, immediately above the calling class in the hierarchy.

Summary

With access modifiers, we can write safe code, hide details, achieve access control. Other users needn't know how we implement details of methods. We provide an interface to other invokers. For access modifiers, you can read Java source code libraries to understand what's the difference. The inheritance, keep in mind the hierarchical structure, is the relationship among classes.

Other Java Tutorials you may like