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 aprotected 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 extendsBadGuy
. 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 theprotected set(String nm)
method ofBadGuy
with a given String and then sets its int field to a given int value. Sinceset(String nm)
method isprotected
it is available to the subclass. - It also has a
toString()
method that calls the superclasstoString()
. - 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.