Define a class named Document that contains an instance variable of type String
ID: 3567793 • Letter: D
Question
Define a class named Document that contains an instance variable of type String
named text that stores any textual content for the document. Create a method
named toString that returns the text field and also include a method to set
this value.
Next, define a class for Email that is derived from Document and includes instance
variables for the sender , recipient , and title of an email message. Implement
appropriate accessor and mutator methods. The body of the email message should
be stored in the inherited variable text . Redefine the toString method to concatenate
all text fields.
Similarly, define a class for File that is derived from Document and includes a
instance variable for the pathname . The textual contents of the file should be stored
in the inherited variable text . Redefine the toString method to concatenate all
text fields.
Finally, create several sample objects of type Email and File in your main method.
Test your objects by passing them to the following subroutine that returns true if
the object contains the specified keyword in the text property.
public static boolean ContainsKeyword(Document docObject,
String keyword)
{
if (docObject.toString().indexOf(keyword,0) >= 0)
return true ;
return false ;
}
Explanation / Answer
Here you go :)
//Dcoument class
public class Document
{
String text;
public void setText(String text) {
this.text = text;
}
public String toString()
{
return this.text;
}
}
//Email class
public class Email extends Document
{
private String sender,recipient ,title;
public String getSender() {
return this.sender;
}
public String getRecipient() {
return this.recipient;
}
public String getTitle() {
return this.title;
}
public void setSender(String sender) {
this.sender = sender;
}
public void setRecipient(String recipient) {
this.recipient = recipient;
}
public void setTitle(String title) {
this.title = title;
}
public String toString()
{
return this.sender+" "+this.recipient+" "+this.title+" "+this.text;
}
}
//File class
public class File extends Document
{
private String pathname;
public String getPathname() {
return pathname;
}
public void setPathname(String pathname) {
this.pathname = pathname;
}
public String toString()
{
return this.pathname+" "+this.text;
}
}
//Test class
public class Test
{
public static boolean ContainsKeyword(Document docObject,String keyword)
{
if (docObject.toString().indexOf(keyword,0) >= 0)
return true ;
return false ;
}
public static void main(String[] args)
{
Email e=new Email();
e.setTitle("a");e.setSender("b");e.setRecipient("c");e.setText("d");
File f=new File();
f.setPathname("z");f.setText("x");
if(ContainsKeyword(e, "a"))System.out.println(e.toString());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.