Yedya
Yedya

Reputation: 15

Quick Java inheritance

Ok so just practicing questions from my textbook for Christmas finales but I sometimes don't understand what some of the questions want.

I'm a bit lost,does it want me to inherit Email tester class?

Question : Create a class EmailTester with a main method which uses the Message class to make a message and print it.

public class Message{    
    String rep;
    String send;
    String mess = "message";


    public Message(String rep,String send){
        rep = "recipient";
        send = "sender";
        mess="";

    }
    public  void append(){          
        mess = " "+"blah blah";         
    }

    public String toString(){           
        mess = "From: Santa Clause\nTo: Rudolf Reindeer\n . . ."; 
        return mess;
    }
}

--

public class EmailTester {
    public static void main(String[] args){
        //?
    }    
}

Upvotes: 0

Views: 78

Answers (5)

Vidya
Vidya

Reputation: 30310

Change your constructor to look like this:

public Message(String recipient, String sender){
        this.recipient = recipient;
        this.sender = sender;
        body = "";
}

The variable names don't matter, but I think they are more intuitive. The main point is that you want each instance of Message to store the values used to construct it.

Then in EmailTester, you do something like this:

Message m = new Message("recipient", "sender");

You will have to ask your professor what it means to "send" a message in this context.

As for inheritance, I have no idea how it applies. Perhaps your instructor is looking to expand things in a future exercise so you have different kinds of messages.

Upvotes: 0

Nishant
Nishant

Reputation: 1142

EmailTester with a main method which uses the Message class to make a message and print it.

Clearly it states has a relationship(composition). EmailTester has a Message. No inheritance is required.

Inheritance is applied when you can sense is a relationship. e.g Car and Vehicle.

Upvotes: 0

Robin Green
Robin Green

Reputation: 33073

You don't need something so complicated as inheritance. If your course was any good, you should have learned about creating objects first, and inheritance later, because inheritance makes no sense without first understanding creating simple objects!

String output = new Message("foo", "bar").toString();

then print that String.

Upvotes: 1

MitchBroadhead
MitchBroadhead

Reputation: 899

Message message = new Message("blah", "blah"):

Upvotes: 0

Juned Ahsan
Juned Ahsan

Reputation: 68715

A class should inherit another class only when it shares "is a relationship".

  • EmailTester is a Message : Does not sound correct
  • Suppose if there is an Email class then, Email is a message - sounds correct

So in your case, no need to extend Message class, rather create an instance of Message class and do the needful.

Upvotes: 0

Related Questions