Question

In: Computer Science

7. When a class contains objects of another class, the relationship is called a whole-part relationship...

7. When a class contains objects of another class, the relationship is called a whole-part relationship or composition. The relationship created is also called a has-a relationship. Discuss some of the possible issues with composition, such CIS216 – Programming Principles Object-Oriented Programming as the long statement: output sales.getHighestPaidEmployee().getHireDate().getYear(). 8. Describe the rules that govern the attributes of a parent class that can be accessed by a child class and the reverse 9. Discuss the advantages of using inheritance and why superclass code is considered more reliable. 10.Research how a derived class can access the constructor of its parent class. 11.Research the topic of multiple inheritance. Describe this concept and explain how it is commonly used in object-oriented programming languages. 12.Create a try–catch block to accept a birth date, entered separately as month, day, and year. Included should be checks for month (1–12), day (28, 29 [if you dare], 30, and 31 days), and year (<= this year).

Solutions

Expert Solution

Ans 7]
HAS-A Relationship:

Composition(HAS-A) simply mean the use of instance variables that are references to other objects. For example Maruti has Engine, or House has Bathroom.
Let’s understand these concepts with an example of Car class.
package relationships;
class Car {
   // Methods implementation and class/Instance members
   private String color;
   private int maxSpeed;
   public void carInfo(){
       System.out.println("Car Color= "+color + " Max Speed= " + maxSpeed);
   }
   public void setColor(String color) {
       this.color = color;
   }
   public void setMaxSpeed(int maxSpeed) {
       this.maxSpeed = maxSpeed;
   }
}
As shown above, Car class has a couple of instance variable and few methods. Maruti is a specific type of Car which extends Car class means Maruti IS-A Car.

class Maruti extends Car{
   //Maruti extends Car and thus inherits all methods from Car (except final and static)
   //Maruti can also define all its specific functionality
   public void MarutiStartDemo(){
       Engine MarutiEngine = new Engine();
       MarutiEngine.start();
       }
   }
Maruti class uses Engine object’s start() method via composition. We can say that Maruti class HAS-A Engine.
package relationships;
public class Engine {
   public void start(){
       System.out.println("Engine Started:");
   }
   public void stop(){
       System.out.println("Engine Stopped:");
   }
}
RelationsDemo class is making object of Maruti class and initialized it. Though Maruti class does not have setColor(), setMaxSpeed() and carInfo() methods still we can use it due to IS-A relationship of Maruti class with Car class.
package relationship
public class RelationsDemo {
   public static void main(String[] args) {      
       Maruti myMaruti = new Maruti();
       myMaruti.setColor("RED");
       myMaruti.setMaxSpeed(180);
       myMaruti.carInfo();
       myMaruti.MarutiStartDemo();
   }
}
Ans 8]
As we know, a child inherits the properties from his parents. A similar concept is followed in Java, where we have two classes:

1. Parent class ( Super or Base class )

2. Child class ( Subclass or Derived class )

A class which inherits the properties is known as Child Class whereas a class whose properties are inherited is known as Parent class.

Syntax:
Now, to inherit a class we need to use extends keyword. In the below example, class Son is the child class and class Mom is the parent class. The class Son is inheriting the properties and methods of Mom class.
class Son extends Mom
{
//your code
}
Ans 9]
Advantages of using inheritance-:

One of the key benefits of inheritance is to minimize the amount of duplicate code in an application by sharing common code amongst several subclasses. Where equivalent code exists in two related classes, the hierarchy can usually be refactored to move the common code up to a mutual superclass. This also tends to result in a better organization of code and smaller, simpler compilation units.
Inheritance can also make application code more flexible to change because classes that inherit from a common superclass can be used interchangeably. If the return type of a method is superclass
Reusability - facility to use public methods of base class without rewriting the same.
Extensibility - extending the base class logic as per business logic of the derived class.
Data hiding - base class can decide to keep some data private so that it cannot be altered by the derived class
Overriding -With inheritance, we will be able to override the methods of the base class so that meaningful implementation of the base class method can be designed in the derived class.
Ans 10]
A derived Java class can call a constructor in its base class using the super keyword. In fact, a constructor in the derived class must call the super's constructor unless default constructors are in place for both classes.
super () can be used to invoke immediate parent class constructor.
As we know, when an object of a class is created, its default constructor is automatically called.

To explicitly call the superclass constructor from the subclass constructor, we use super(). It's a special form of the super keyword.

super() can be used only inside the subclass constructor and must be the first statement.
Example:
class Animal {

// default or no-arg constructor of class Animal
Animal() {
System.out.println("I am an animal");
}
}

class Dog extends Animal {

// default or no-arg constructor of class Dog
Dog() {

// calling default constructor of the superclass
super();

System.out.println("I am a dog");
}
}

class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
}
}
Ans 11]
Multiple inheritance a feature of some object-oriented programming languages in which a class or an object inherits characteristics and properties from more than one parent class or object. This is contrary to the single inheritance property, which allows an object or class to inherit from one specific object or class. Although there are certain benefits associated with multiple inheritance, it does increase ambiguity and complexity when not designed or implemented properly.
/Base Class
class A
{
public void fooA()
{
//TO DO:
}
}

//Base Class
class B
{
public void fooB()
{
//TO DO:
}
}

//Derived Class
class C : A, B
{
public void fooC()
{
// TO DO
}
}


Related Solutions

(32%) Create a class of function objects called StartsWith that satisfies the following specification: when initialized...
(32%) Create a class of function objects called StartsWith that satisfies the following specification: when initialized with character c, an object of this class behaves as a unary predicate that determines if its string argument starts with c. For example, StartsWith(’a’) is a function object that can be used as a unary predicate to determine if a string starts with an a. So StartsWith(’a’)("alice") would return true but StartsWith(’a’)("bob") would return false. The function objects should return false when called...
Step 4: Create a class called BabyNamesDatabase This class maintains an ArrayList of BabyName objects. Instance...
Step 4: Create a class called BabyNamesDatabase This class maintains an ArrayList of BabyName objects. Instance Variables Declare an ArrayList of BabyName objects. Constructor public BabyNamesDatabase () - instantiate the ArrayList of BabyName objects. You will not insert the items yet. This method will be one line of code. Mutator Methods public void readBabyNameData(String filename) - open the provided filename given as input parameter, use a loop to read all the data in the file, create a BabyName object for...
Python Create a move function that is only defined in the base class called Objects. The...
Python Create a move function that is only defined in the base class called Objects. The move function will take two parameters x,y and will also return the updated x,y parameters.
AskInfoPrintInfo Write a program called AskInfoPrintInfo. It should contain a class called AskInfoPrintInfo that contains the...
AskInfoPrintInfo Write a program called AskInfoPrintInfo. It should contain a class called AskInfoPrintInfo that contains the method main. The program should ask for information from the user and then print it. Look at the examples below and write your program so it produces the same input/output. Examples (the input from the user is in bold face) % java AskInfoPrintInfo enter your name: jon doe enter your address (first line): 23 infinite loop lane enter your address (second line): los angeles,...
Write a class called Animal that contains a static variable called count to keep track of...
Write a class called Animal that contains a static variable called count to keep track of the number of animals created. Your class needs a getter and setter to manage this resource. Create another variable called myCount that is assigned to each animal for each animal to keep track of its own given number. Write a getter and setter to manage the static variable count so that it can be accessed as a class resource
Step1 - Define two classes, Whole and part. Use a strong "has a" relationship with the...
Step1 - Define two classes, Whole and part. Use a strong "has a" relationship with the two classes.             Constructor Functions             Define a default constructor for the Part class.                         Default just prints out "In default part constructor"             Define a default and a parm constructor for the Whole class.                         In Whole Default constructor assigns wholeName = "None"; and prints out "In whole default Constructor"                         In Whole Parm constructor - Passes in name to WholeName and                        ...
Part 1 – Classes and objects Create a new Java project called usernamePart1 in NetBeans. In...
Part 1 – Classes and objects Create a new Java project called usernamePart1 in NetBeans. In my case the project would be called rghanbarPart1. Select the option to create a main method. Create a new class called Vehicle. In the Vehicle class write the code for: • Instance variables that store the vehicle’s make, model, colour, and fuel type • A default constructor, and a second constructor that initialises all the instance variables • Accessor (getters) and mutator (setters) methods...
python Design a class named IP_address to represent IP address objects. The IP_addressclass contains the following...
python Design a class named IP_address to represent IP address objects. The IP_addressclass contains the following A number of instance variables/fields to store a table of data. You can design them by your own. A constructor that creates a table with the following: a list of data. ip address a integer to indicate the number of elements in the sum_list/freq_list/average_list A get_ip_address() method that returns the ip address For example, consider the following code fragment: ip_key = '192.168.0.24' data_list =[(0,...
Python Design a class named IP_address to represent IP address objects. The IP_addressclass contains the following...
Python Design a class named IP_address to represent IP address objects. The IP_addressclass contains the following A number of instance variables/fields to store a table of data. You can design them on your own. A constructor that creates a table with the following: a list of data. IP address an integer to indicate the number of elements in the sum_list/freq_list/average_list A get_ip_address() method that returns the IP address For example, consider the following code fragment: ip_key = '192.168.0.24' data_list =[(0,...
Java program Write a class called Animal that contains a static variable called count to keep...
Java program Write a class called Animal that contains a static variable called count to keep track of the number of animals created. Your class needs a getter and setter to manage this resource. Create another variable called myCount that is assigned to each animal for each animal to keep track of its own given number. Write a getter and setter to manage the static variable count so that it can be accessed as a class resource
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT