Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java Eclipse Understand the Classes and Problem Every message contains some cont

ID: 3668469 • Letter: J

Question

Java Eclipse

Understand the Classes and Problem

Every message contains some content ("The British are coming! The British are coming!"). We could enhance this by adding other traits (author, date and/or time of creation), but let's keep things simple and say that this is the only aspect of a basic message.

Some messages, however, have further components that define them. For example, an email consists of a normal message, plus at least two other items: a from email address and ato email address. An email is a message, but a special kind of message. So we can smell inheritance in the neighborhood. A message seems like it will make a good base class, and an email, having an is a relationship with message, is a good candidate for a derived class or extension of the base class message.

Meanwhile, a tweet consists of a normal message, plus at least one other item: a from user id. An tweet is a message, too. It has a different kind of specialization than an email has, so it is a different extension of the base class. (We are not considering a direct tweet, which would also require a to user id.)

Not only will both emails and tweets contain extra data than the base class, message, but in at least one instance we will see the same member (the content) have a different kind of restriction in the derived class than in the base class (can you guess what I'm suggesting before you read on?). Thus, even though we store the tweet content in the base class member, without the need for a new content area for the tweet, we will still have a different validation of the length of that message content.

Warning: Because it makes sense to do so, we are going to name the message content message and the message class Message. So what I called content in the above paragraph will be known as (lower-case) message in what comes next. The class, itself, will be (upper-case) Message. You'll see. Just keep reading.

File Structure: You will use one file for the entire program, so the non-Foothill classes should be non-public.

The Base Class: Message

Your base class is named Message.

Public or Protected (your choice) Static Class Constants

Define a full set of limits and defaults, like MAX_MSG_LENGTH, for both min, max length and default data of the member. Set the maximum message length to 100,000.

Private Member Data

Public Methods

Default and 1-parameter constructors.

Mutator and Accessor for the member.

a toString() method that provides a nicely formatted return String for potential screen I/O.

Private Methods

private static validation helper to filter client parameters. These will support your public methods.

Recommended test of Class Message

Instantiate two or more Message objects, some using the default constructor and some using the parameter-taking constructor. Mutate the member, and after that use the toString()to assist a screen output so we can see what all of your objects contain. Next, test the accessor. Finally, test the mutator, providing both legal and illegal arguments and testing the return values (thus demonstrating that the mutator does the right thing). Here is a sample run from my test (but you will have to imagine/deduce the source I used and create your ownsource for your testing, which will produce a different output).

Example Test Run of Message Class

The Derived Class: Email

Your first derived class is named Email. Email uses the member already present in the base class; the Email's message is the message of the base class. Do not try to store anEmail's message body as a new member of the derived class or you will get get a 0 on the assignment -- not desirable by you or me. Duplicating base class data in derived class means you do not understand what inheritance is, thus the significance of this kind of mistake.

Public Static Class Constants

To the existing base class statics, add at least two with names and meanings similar or identical to MAX_EMAIL_ADDRESS_LENGTH and DEFAULT_EMAIL_ADDRESS. Look up the maximum length of an email address, and make sure yours is no larger than that (but you can make it smaller for easier testing).

Additional Private Member Data

Public Methods

Default and 3-parameter constructors. Use constructor chaining.

Mutators and Accessors for the new members.

Override those methods of the base class for which it makes sense to do so. Think about this and come to your own conclusions.

Private Methods

private static validation helper to filter a bad email address. You should do the minimum, but you don't have to be more complete than that. This is just to show that you can perform basic filtering. The minimum is a method isValidEmailAddress(), which tests for both length and the existence of at least one '@' and one '.' character. Further is up to you, but don't overdo it or be too restrictive.

Recommended test of Class Email

Similar to the Message class.

Example Test Run of Email Class (done in same run as overall program run)

The Derived Class: Shweet

(It is like a Twitter Tweet, but since I can't be certain that the details of a Tweet are exactly what I state here, we will disengage this from Twitter, and make the constraints that I impose accurate for a Shweet by decree.)

Shweet uses the member already present in the base class; The Shweet's message is the message of the base class. Do not try to store a Shweet's message body as a new member or you will get a 0 on the assignment, as mentioned above.

Public Static Class Constants

To the existing base class statics, add three: MAX_SHWITTER_ID_LENGTH (15), MAX_SHWEET_LENGTH (140) and DEFAULT_USER_ID.

While the MAX_SHWEET_LENGTH is going to be smaller than the base class's MAX_MSG_LENGTH, do not assume this fact in your implementation. A valid message length for aShweet has to be smaller than both of these values. If it's not a valid base class message, it isn't a valid Shweet message, and this should be true if we later change the MAX_SHWEET_LENGTH length to be 50 million.

Additional Private Member Data

Public Methods

Default and 2-parameter constructors. When it is possible and meaningful, use constructor chaining. Think about which constructor to chain to.

Mutator and Accessor for the new member.

Override those methods of the base class for which it makes sense to do so. Think about this and come to your own conclusions. You have to somehow enforce the length limits of both the base class and the derived class for the same message member.

Private Methods

private static validation helpers (plural) to filter out bad tweets and shwitter IDs. Create an isValidShweet() for the message. Also, create an isValidShwitterID() for theShwitter ID. But also, make a third, even lower-level, helper that would make isValidShwitterID() clear and short. This helper-helper should be namedstringHasOnlyAlphaOrNumOrUnderscore() and that name tells you the kind of thing it should do: it should make sure the shwitter ID contains only some combination of letters, numbers or an underscore ('_').     Also, I don't care whether you decide that the Shwitter ID be case sensitive. If you don't know what String or Character methods can be used for this, look them up online. They are very easy to find.

Recommended test of Class Shweet

Similar to the Message class.

Example Test Run of Shweet Class (done in same run as overall program run)

Explanation / Answer

class HelloWorld{
   public static void main(String[] args)
   {
      Message testMsg1, testMsg2, testMsg3;
      testMsg1 = new Message();
      testMsg2 = new Message("My life for Aiur!");
      testMsg3 = new Message("");
    
      String longString = new String("LOL");
    
      while (longString.length() < Message.MAX_MSG_LENGTH + 1)
         longString += "LOLLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOL";
    
      System.out.println("---Tests of Base Class---- ");
    
      //Show initial messages using toString()
      System.out.println("---Initial messages using toString(): " +
                         "Message 1: " + testMsg1.toString() +
                         "Message 2: " + testMsg2.toString() +
                         "Message 3: " + testMsg3.toString());
    
      //Mutate some members then display all w/ toString()
      testMsg1.setMessage("Goodbye cruel world!");
      testMsg3.setMessage("IT IS GOOD TO BE A VALID MESSAGE!");
    
      System.out.println("---Mutated msg1, msg3. Showing w/ toString(): " +
                         "Message 1: " + testMsg1.toString() +
                         "Message 2: " + testMsg2.toString() +
                         "Message 3: " + testMsg3.toString());
    
      //Testing accessor
      System.out.println("---Testing message accessor: " +
                         " Message 1: " + testMsg1.getMessage() +
                         " Message 2: " + testMsg2.getMessage() +
                         " Message 3: " + testMsg3.getMessage());
    
      //Testing mutator
      System.out.println("---Testing message mutator: ");
      if (testMsg1.setMessage("k"))
         System.out.println("Successfully mutated testMsg1");
      else
         System.out.println("Failed to mutate testMsg1");
    
      if (testMsg2.setMessage(longString))
         System.out.println("Successfully mutated testMsg2");
      else
         System.out.println("Testmsg2 mutate too long (expected)");
    
      if (testMsg3.setMessage(""))
         System.out.println("Successfully mutated testMsg3! ");
      else
         System.out.println("Testmsg3 mutate too short (expected) ");
    
    
    
   }

}

class Message
{
   //--static class constants
   public static final int MIN_MSG_LENGTH = 1;
   public static final int MAX_MSG_LENGTH = 100000;
   public static final int DEFAULT_MSG_LENGTH = 10;
   public static final String DEFAULT_MSG = "Hello world!";

   //--private member data
   private String message;

   //--public class methods
   public Message()
   {
      message = new String(DEFAULT_MSG);
   }
   public Message(String userMessage)
   {
      if (!validMessage(userMessage))
         message = new String(DEFAULT_MSG);
      else
         message = new String(userMessage);
    
   }
   public String getMessage()
   {
      return message;
   }
   public boolean setMessage(String messageInput)
   {
      if (!validMessage(messageInput))
         return false;
    
      message = messageInput;
      return true;
   }
   public String toString()
   {
    
      String returnString = new String("***** BEGIN MESSAGE ***** ");
      if (validMessage(message))
         returnString += message;
    
      returnString += " ***** END MESSAGE ***** ";
    
      return returnString;
   }
   //--private class methods

   private boolean validMessage(String testMessage)
   {
      if (testMessage.length() > MAX_MSG_LENGTH ||
          testMessage.length() < MIN_MSG_LENGTH)
         return false;
    
      return true;
   }
    

}

Email.java

public class Email extends Message
{
    // class constants
    public final static int MIN_EMAIL_ADDRESS_LENGTH = 7;
    public final static int MAX_EMAIL_ADDRESS_LENGTH = 100;
    public final static String DEFAULT_EMAIL_ADDRESS = "vince@gmail.com";

    // private members
    private String fromAddress;
    private String toAddress;

    public Email(String theAuth, String theMsg, String fromAddr, String toAddr)
    {
        set(theAuth, theMsg, fromAddr, toAddr);
    }

    public Email()
    {
        this(DEFAULT_AUTHOR, DEFAULT_MESSAGE,
                DEFAULT_EMAIL_ADDRESS, DEFAULT_EMAIL_ADDRESS);
    }

    private boolean set(String theAuth, String theMsg,
            String fromAddr, String toAddr)
    {

        final boolean authorValid = super.setAuthor(theAuth);
        final boolean messageValid = super.setMessage(theMsg);
        final boolean toAddressValid = setFromAddress(fromAddr);
        final boolean fromAddressValid = setToAddress(toAddr);

        if (!authorValid || !messageValid ||
                !toAddressValid || !fromAddressValid)
            return false;

        return true;
    }

    public boolean setFromAddress(String fromAddress)
    {
        final boolean lengthValid = isValidLength(fromAddress,
                MIN_EMAIL_ADDRESS_LENGTH, MAX_EMAIL_ADDRESS_LENGTH);
        final boolean emailValid = isValidEAddr(fromAddress);

        if (!lengthValid || !emailValid)
            return false;

        this.fromAddress = fromAddress;
        return true;
    }

    public boolean setToAddress(String toAddress)
    {
        final boolean lengthValid = isValidLength(toAddress,
                MIN_EMAIL_ADDRESS_LENGTH, MAX_EMAIL_ADDRESS_LENGTH);
        final boolean emailValid = isValidEAddr(toAddress);

        if (!lengthValid || !emailValid)
            return false;

        this.toAddress = toAddress;
        return true;
    }

    public String getFromAddress()
    {
        return fromAddress;
    }

    public String getToAddress()
    {
        return toAddress;
    }

    //Validation helpers
    private boolean isValidLength(String testString, int min, int max)
    {
        if (testString == null || testString == "" ||
                testString.length() < min || testString.length() > max)
            return false;
        return true;
    }

    private boolean isValidEAddr(String emailAddress)
    {
        if (emailAddress == null || emailAddress == "")
            return false;

        final boolean hasAtSign = emailAddress.contains("@");
        final boolean hasPeriod = emailAddress.contains(".");

        if (!hasAtSign || !hasPeriod)
            return false;

        return true;
    }

    public String toString()
    {
        String returnString;

        returnString = "From: " + fromAddress + " To: " +
                toAddress + " " + super.toString();

        return returnString;
    }
}

Shweet.java

public class Shweet extends Message
{
    // class constants
    public final static int MIN_SHWITTER_ID_LENGTH = 3;
    public final static int MAX_SHWITTER_ID_LENGTH = 15;
    public final static int MIN_SHWEET_LENGTH = 5;
    public final static int MAX_SHWEET_LENGTH = 140;
    public final static String DEFAULT_USER_ID = "default_user";

    // private members
    private String fromID;

    public Shweet(String theAuth, String theMsg, String theID)
    {
        set(theAuth, theMsg, theID);
    }

    public Shweet()
    {
        this(DEFAULT_AUTHOR, DEFAULT_MESSAGE, DEFAULT_USER_ID);
    }

    public boolean set(String theAuth, String theMsg, String theID)
    {
        final boolean authorValid = super.setAuthor(theAuth);
        final boolean messageValid = setMessage(theMsg);
        final boolean iDValid = setFromID(theID);

        if (!authorValid || !messageValid || !iDValid)
            return false;

        return true;
    }

    public boolean setFromID(String fromID)
    {
        final boolean shwittertIDValid = isValidShwitterID(fromID);

        if (!shwittertIDValid)
            return false;

        this.fromID = fromID;
        return true;
    }

    public String getFromID()
    {
        return fromID;
    }

    //I'm overridding setMessage because we have to test
    //the schweet length in this class too
    public boolean setMessage(String shweetMessage)
    {
        final boolean shweetValid = isValidShweet(shweetMessage);

        if (!shweetValid)
            return false;

        if (!super.setMessage(shweetMessage))
            return false;

        return true;
    }

    //validation helpers
    private boolean isValidShweet(String shweetMessage)
    {
        final boolean shweetLengthValid = isValidLength(shweetMessage,
                MIN_SHWEET_LENGTH, MAX_SHWEET_LENGTH);

        if (!shweetLengthValid)
            return false;

        return true;
    }

    private boolean isValidShwitterID(String theID)
    {
        final boolean lengthValid = isValidLength(theID,
                MIN_SHWITTER_ID_LENGTH, MAX_SHWITTER_ID_LENGTH);
        final boolean styleValid = stringHasOnlyAlphaOrNumOrUnderscore(theID);

        if (!lengthValid || !styleValid)
            return false;

        return true;
    }

    private boolean stringHasOnlyAlphaOrNumOrUnderscore(String theID)
    {
        if (theID == null || theID == "")
            return false;

        int k;

        for (k = 0 ; k < theID.length() ; k++)
        {
            if (!Character.isLetterOrDigit(theID.charAt(k)) &&
                    !(theID.charAt(k) == '_'))
                return false;
        }

        return true;
    }

    private boolean isValidLength(String testString, int min, int max)
    {
        if (testString == null || testString == "" ||
                testString.length() < min || testString.length() > max)
            return false;
        return true;
    }

    public String toString()
    {
        String returnString;

        returnString = "Shweet: " + super.getAuthor() + "@" + fromID + " "
                + super.getMessage() + " ";

        return returnString;
    }
}


sample output

---Tests of Base Class----                                                                                                                                  
---Initial messages using toString():                                                                                                                       
                                                                                                                                                            
Message 1:                                                                                                                                                  
***** BEGIN MESSAGE *****                                                                                                                                   
                                                                                                                                                            
Hello world!                                                                                                                                                
                                                                                                                                                            
***** END MESSAGE *****                                                                                                                                     
                                                                                                                                                            
Message 2:                                                                                                                                                  
***** BEGIN MESSAGE *****                                                                                                                                   
***** END MESSAGE *****                                                                                                                                     
                                                                                                                                                            
Message 3:                                                                                                                                                  
***** BEGIN MESSAGE *****                                                                                                                                   
                                                                                                                                                            
Hello world!                                                                                                                                                
                                                                                                                                                            
***** END MESSAGE *****                                                                                                                                     
---Mutated msg1, msg3. Showing w/ toString():                                                                                                               
                                                                                                                                                            
Message 1:                                                                                                                                                  
***** BEGIN MESSAGE *****                                                                                                                                   
                                                                                                                                                            
Goodbye cruel world!                                                                                                                                        

***** END MESSAGE *****                                                                                                                                     
                                                                                                                                                            
Message 2:                                                                                                                                                  
***** BEGIN MESSAGE *****                                                                                                                                   
                                                                                                                                       

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote