TurkuBasicOOPinJava / Week 5: Class hierarchies /09A. Calling parent class methods [ENCAPSULATION]
KaiquanMah's picture
child class method overwrites parent class method
3f5b26b verified
raw
history blame
2.23 kB
A child class can call parent class's methods.
This is useful, for example, when a method is reimplemented in a child class,
but you want to use the CHILD class IMPLEMENTATION as a BASE.
Consider the example of the class Message:
class Message {
protected String sender;
protected String msg;
public Message(String sender, String msg) {
this.sender = sender;
this.msg = msg;
}
public String getMsg() {
return "Sender: " + sender + "\n\n" + msg;
}
}
The 'SecretMessage' class inherits the 'Message' class.
The class has been reimplemented with the method getMsg.
However, the reimplemented method requests a message from the child/inheriting class only, which is then "encrypted":
class SecretMessage extends Message {
public SecretMessage(String sender, String msg) {
super(sender, msg);
}
// Overwritten method, which calls parent class's corresponding
// method and then "encypts" the message.
public String getMsg() {
String content = super.getMsg();
String secretmsg = "";
for (int i=0; i<content.length(); i++) {
// ADD '1' to each character of the string
// then append to the 'secretmsg' STRING
secretmsg += (char) (content.charAt(i) + 1);
}
return secretmsg;
}
}
An example of calling classes:
public static void main(String[] args) {
Message m = new Message("Pete Public", "Hello.");
SecretMessage sm = new SecretMessage("Sam Secret", "Hello.");
System.out.println("Class message:");
System.out.println(m.getMsg());
System.out.println();
System.out.println("Class SecretMessage :");
System.out.println(sm.getMsg());
}
Program outputs:
Class message:
Sender: Pete Public
Hello.
Class SecretMessage:
Ifmmp/
Note that CLIENTS of a CHILD class have NO ACCESS to a feature of the PARENT class
if it has been REIMPLEMENTED (i.e. OVERWRITTEN) in the child class.
This follows the basic principle of encapsulation: the class decides which features the client has access to.
Thus, clients of an entity of type SecretMessage cannot call the method getMsg of the Message class in any way.