Spaces:
Running
Running
File size: 2,225 Bytes
3f5b26b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | 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.
|