Question

Please I need help with the following questions in JAVA programming language. Please comment the code...

Please I need help with the following questions in JAVA programming language. Please comment the code to help me understand, thanks.

Exercise 1: Inheritance

1. Firstly, create and compile a simple class called Parent. Give it the following behaviour:
a. A default constructor that does nothing other than print out “Parent default
constructor” using System.out
b. A single method called getMessage which returns a String, e.g. “Parent message”
2. Next, create and compile a class called Child. Give it the following behaviour
a. Do not give it a constructor
b. Override the parent’s getMessage method to return an alternative String. E.g.
“Child message”
c. A main method which creates an instance of the Child object, and then writes the
value returned by its getMessage method to the command line.
d. What happens when the class is run?
3. Alter the Child class to give it a default constructor which prints out “Child default
constructor”. Compile and run the application again and identify what happens.
4. Alter the implementation of the getMessage method in the Child class so that it first
calls the parent class method, then concatenates the result with its own value to build a
combined message. E.g. returning “Parent message and Child message”.
5. Alter the Parent class by
a. Adding a new constructor that accepts a String argument. This should be used to
initialise a private member variable, myMessage. Again write a message to the
console that indicates that the constructor has been called.
b. Alter the getMessage method so that it returns the value of the myMessage
rather than a fixed message.
c. Now alter the Child class so that it from its default constructor it calls the new
constructor on the parent class.
6. Alter the myMessage member variable in the Parent class so that it is declared to be
protected. Confirm that the Child class can now refer to the variable directly, rather
than having to call its parent’s version of getMessage to build the combined message.
Can you think of the pros and cons of the two different mechanisms?


Exercise 2: Abstract Classes and Methods

1. Create an abstract class called AbstractParent. Give it the following two methods:
a. A public method called getMessage that accepts no parameters and returns a
String. This method should call a second method, generateString that again
just returns a String.
b. Define generateString so that it a protected abstract method.
2. Create a second class called SecondChild, which extends AbstractParent.
a. Implement the generateString method defined by its parent to return a
suitable String
b. Add a main method that creates an instance of SecondChild and invokes its
getMessage method. Can you identify what is happening here?

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Exercise 1: Inheritance

2.

d. What happens when the class is run?

public class Parent {
    public Parent(){
        System.out.println("Parent default constructor");
    }


    public String getMessage(){
        return "Parent Message";
    }

}
public class Child extends Parent {


    @Override
    public String getMessage() {
        return "Child Message";
    }

    public static void main(String[] args) {
        Child c = new Child();
        System.out.println(c.getMessage());
    }

}

OUTPUT

Parent default constructor
Child message

3.

public class Parent {
    public Parent(){
        System.out.println("Parent default constructor");
    }


    public String getMessage(){
        return "Parent Message";
    }

}
public class Child extends Parent {

    public Child() {
        System.out.println("Child default constructor");
    }

    @Override
    public String getMessage() {
        return "Child Message";
    }

    public static void main(String[] args) {
        Child c = new Child();
        System.out.println(c.getMessage());
    }

}

OUTPUT

Parent default constructor
Child default constructor
Child Message

4.

public class Parent {
    public Parent(){
        System.out.println("Parent default constructor");
    }


    public String getMessage(){
        return "Parent Message";
    }

}
public class Child extends Parent {

    public Child() {
        System.out.println("Child default constructor");
    }

    @Override
    public String getMessage() {
        return super.getMessage()+" Child Message";
    }

    public static void main(String[] args) {
        Child c = new Child();
        System.out.println(c.getMessage());
    }

}

OUTPUT

Parent default constructor
Child default constructor
Parent Message Child Message

After point 6 code will look like

//Parent.java

public class Parent {
    protected String myMessage;
    public Parent(){
        System.out.println("Parent default constructor");
    }

    // 5.a
    public Parent(String myMessage) {
        this.myMessage = myMessage;
        System.out.println("Parent constructor with String argument ");
    }

    public String getMessage(){
        return myMessage; // 5.b
    }

}

//Child.java

public class Child extends Parent {

    public Child() {
        super(""); // 5.c
        System.out.println("Child default constructor");
    }

    @Override
    public String getMessage() {
        // modifying the parent class variable myObject as it was protected
        super.myMessage = "child object message"; // 6
        return super.getMessage() + " Child Message"; // 4
    }

    public static void main(String[] args) {
        Child c = new Child();
        System.out.println(c.getMessage());
    }

}

// OUTPUT

Parent constructor with String argument
Child default constructor
child object message Child Message

Can you think of the pros and cons of the two different mechanisms?

pros:

protected variable can be access like public but within the package only

cons:

as it is protected any object can alter this and lets suppose if any validation required that will never apply, that can result malformed.

Exercise 2: Abstract Classes and Methods

//AbstractParent.java
public abstract class AbstractParent {
    public String getMessage(){
        return generateString();
    }

    protected abstract String generateString();
}

//SecondChild.java

public class SecondChild extends AbstractParent {

    @Override
    protected String generateString() {
        return "SecondChild Message";
    }

    public static void main(String[] args) {
        SecondChild sc = new SecondChild();
        System.out.println(sc.getMessage());
    }
}

//OUTPUT

SecondChild Message

Can you identify what is happening here?

ParentAbstract is the abstract class with abstract generateString which is implemented in SecondChild class

when it calls the getMessage it invoke the abstract function and call where its implemented

Add a comment
Know the answer?
Add Answer to:
Please I need help with the following questions in JAVA programming language. Please comment the code...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Need help to create general class Classes Data Element - Ticket Create an abstract class called...

    Need help to create general class Classes Data Element - Ticket Create an abstract class called Ticket with: two abstract methods called calculateTicketPrice which returns a double and getld0 which returns an int instance variables (one of them is an object of the enumerated type Format) which are common to all the subclasses of Ticket toString method, getters and setters and at least 2 constructors, one of the constructors must be the default (no-arg) constructor. . Data Element - subclasses...

  • Java Program Please help me with this. It should be pretty basic and easy but I...

    Java Program Please help me with this. It should be pretty basic and easy but I am struggling with it. Thank you Create a superclass called VacationInstance Variables destination - String budget - double Constructors - default and parameterized to set all instance variables Access and mutator methods budgetBalance method - returns the amount the vacation is under or over budget. Under budget is a positive number and over budget is a negative number. This method will be overwritten in...

  • Needs Help In Java Programming language Exceptional Cars Purpose To review interfaces and exception usage. Directions...

    Needs Help In Java Programming language Exceptional Cars Purpose To review interfaces and exception usage. Directions Your task is to write a class called Car. Your class should have the following fields and methods: private int position private boolean headlightsOn public Car() - a constructor which initializes position to 0 and headlightsOn to false public Car(int position) - a constructor which initializes position to the passed in value and headlightsOn to false, and it should throw a NegativeNumberException with a...

  • Language: C++ Create an abstract base class person. The person class must be an abstract base...

    Language: C++ Create an abstract base class person. The person class must be an abstract base class where the following functions are abstracted (to be implemented in Salesman and Warehouse): • set Position • get Position • get TotalSalary .printDetails The person class shall store the following data as either private or protected (i.e., not public; need to be accessible to the derived classes): . a person's name: std::string . a person's age: int . a person's height: float The...

  • Write the Java code for the class WordCruncher. Include the following members:

    **IN JAVAAssignment 10.1 [95 points]The WordCruncher classWrite the Java code for the class WordCruncher. Include the following members:A default constructor that sets the instance variable 'word' to the string "default".A parameterized constructor that accepts one String object as a parameter and stores it in the instance variable. The String must consist only of letters: no whitespace, digits, or punctuation. If the String parameter does not consist only of letters, set the instance variable to "default" instead. (This restriction will make...

  • Code in JAVA UML //TEST HARNESS //DO NOT CHANGE CODE FOR TEST HARNESS import java.util.Scanner; //...

    Code in JAVA UML //TEST HARNESS //DO NOT CHANGE CODE FOR TEST HARNESS import java.util.Scanner; // Scanner class to support user input public class TestPetHierarchy { /* * All the 'work' of the process takes place in the main method. This is actually poor design/structure, * but we will use this (very simple) form to begin the semester... */ public static void main( String[] args ) { /* * Variables required for processing */ Scanner input = new Scanner( System.in...

  • All question base on Java Se 8 Consider the Top class i public abstract class Topí...

    All question base on Java Se 8 Consider the Top class i public abstract class Topí 2 private 3 protected String name; 4 public intx - 12; int age; e public Top(String name)[ this.namename age0; System.out.println(x); 10 12 public abstract void foo(String f); 13 Create a Middle class that extends the Top class. The class should have a single constructor that takes two input parameters: a String (for name) and int (for age). Your constructor should not have any redundant...

  • In Java Create an interface called Amount that includes a method called setPrice (). Create an a...

    In Java Create an interface called Amount that includes a method called setPrice (). Create an abstract class named Book that inherits from the interface Amount. Include a String field for the book’s title and a double field for the book’s Price . Within the class, include a constructor that requires the book title and add two getter methods — one that returns the title and one that returns the price. Include an abstract method named setPrice (). Create a...

  • Please help with a source code for C++ and also need screenshot of output: Step 1:...

    Please help with a source code for C++ and also need screenshot of output: Step 1: Create a Glasses class using a separate header file and implementation file. Add the following attributes. Color (string data type) Prescription (float data type) Create a default constructor that sets default attributes. Color should be set to unknown because it is not given. Prescription should be set to 0.0 because it is not given. Create a parameterized constructor that sets the attributes to the...

  • Java Create four classes: 1.      An Animal class that acts as a superclass for Dog and...

    Java Create four classes: 1.      An Animal class that acts as a superclass for Dog and Bird 2.      A Bird class that is a descendant of Animal 3.      A Dog class that is a descendant of Animal 4.      A “driver” class named driver that instantiates an Animal, a Dog, and a Bird object. The Animal class has: ·        one instance variable, a private String variable named   name ·        a single constructor that takes one argument, a String, used to set...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT