Notice: session_start(): A session had already been started - ignoring in /home/u614325693/domains/onedoubt.com/public_html/post.php on line 3
Java protected Keyword - ONEDOUBT.COM

Example

The Student subclass accesses a Person class with protected attributes:

class Person {

  protected String fname = "John";

  protected String lname = "Doe";

  protected String email = "john@doe.com";

  protected int age = 24;

}

 

class Student extends Person {

  private int graduationYear = 2018;

  public static void main(String[] args) {

    Student myObj = new Student();

    System.out.println("Name: " + myObj.fname + " " + myObj.lname);

    System.out.println("Email: " + myObj.email);

    System.out.println("Age: " + myObj.age);

    System.out.println("Graduation Year: " + myObj.graduationYear);

  }

}


Definition and Usage

The protected keyword is an access modifier used for attributes, methods and constructors, making them accessible in the same package and subclasses.


Related Pages

Read more about modifiers in our Java Modifiers Tutorial.

 


Login
ADS CODE