class

Protected Keyword

This is an example of how to use the protected keyword in a class. In order to use the protected keyword, we have created a class with a protected method and a subclass that uses its protected method:

  • We have created a class, BadGuy that has a String field, myname and a protected void set(String nm) method that sets its field to the given String.
  • It also has a toString() method returning a String message with the String field of the class.
  • We have also created a class, ProtectedKeyWord that extends BadGuy. It has an int field, num.
  • ProtectedKeyWord has a constructor that uses a String and an int field and calls its superclass constructor to initialize its String field to the given String and then it initializes its int field with the given int value.
  • It has a method change(String name, int id) that calls the protected set(String nm) method of BadGuy with a given String and then sets its int field to a given int value. Since set(String nm) method is protected it is available to the subclass.
  • It also has a toString() method that calls the superclass toString().
  • We create a new ProtectedKeyWord object with a given String and a given int field.
  • We call the change(String name, int id) method to the object.
  • The two objects are printed.

Let’s take a look at the code snippet that follows:  

package com.javacodegeeks.snippets.core;


class BadGuy {
  private String myname;

  protected void set(String nm) {
    myname = nm;
  }

  public BadGuy(String name) {
    this.myname = name;
  }

  public String toString() {
    return "I'm a BadGuy and my name is " + myname;
  }
}

public class ProtectedKeyWord extends BadGuy {
  private int num;

  public ProtectedKeyWord(String name, int orcNumber) {
    super(name);
    this.num = orcNumber;
  }

  public void change(String name, int id) {
    set(name); // Available because it's protected
    this.num = id;
  }

  public String toString() {
    return "Id " + num + ": " + super.toString();
  }

  public static void main(String[] args) {
    ProtectedKeyWord ID = new ProtectedKeyWord("Nikos", 12);
    System.out.println(ID);
    ID.change("Dimitris", 19);
    System.out.println(ID);

  }
} 

Output:

Id 12: I'm a BadGuy and my name is Nikos
Id 19: I'm a BadGuy and my name is Dimitris

  
This was an example of how to use the protected keyword in a class in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button