0% found this document useful (0 votes)
67 views12 pages

OOP Debug 6

The document provides examples and definitions related to inheritance in object-oriented programming. It defines single inheritance as a class inheriting from a single base class, and multiple inheritance as a class inheriting from multiple base classes. It gives an example of multiple inheritance using parents and children. It also discusses abstract classes and interfaces in Java, including their differences and how each achieves abstraction.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views12 pages

OOP Debug 6

The document provides examples and definitions related to inheritance in object-oriented programming. It defines single inheritance as a class inheriting from a single base class, and multiple inheritance as a class inheriting from multiple base classes. It gives an example of multiple inheritance using parents and children. It also discusses abstract classes and interfaces in Java, including their differences and how each achieves abstraction.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

MODULE 06

DEBUG YOUR SKILLS

1. Define and distinguish the terms single inheritance and multiple inheritance.

S.NO Single inheritance

1.Single inheritance is one in which the derived Single inheritance is one in which the derived
class inherits the single base class. class inherits the single base class.

2.In single inheritance, the derived class uses In single inheritance, the derived class uses the
the features of the single base class. features of the single base class.

3.Single inheritance requires small run time as Single inheritance requires small run time as
compared to multiple inheritance due to less compared to multiple inheritance due to less
overhead. overhead.

4.Single inheritance is a lot of close to Single inheritance is a lot of close to


specialization. specialization.

5. Single inheritance is implemented as Class Single inheritance is implemented as Class


DerivedClass_name : access_specifier DerivedClass_name : access_specifier
Base_Class{};. Base_Class{};.

6.Single inheritance is simple in comparison to Single inheritance is simple in comparison to


the multiple inheritance. the multiple inheritance.

7.Single inheritance can be implemented in any Single inheritance can be implemented in any
programming language. programming language.

2. Give an example of multiple inheritance in a real-life situation.

A nice illustration of double inheritance is parents. There are two parents for every child; it's just the
way it is. That you can create classes utilizing multiple inheritance makes sense.

3. A and B are two classes. A inherits properties from B, so A is a ___________ class of B and B is a
__________ class of A.

If A has attributes a1 and a2, methods getA1() and getA2(), and B has attributes b1 and b2, methods
getB1() and getB2(), then by means of inheritance, the actual definition of A and B would be:

 NOT YET ANSWERED


4. Given the following information on classes A and B, declare A and B in Java:

 attributes a1, b1 are integers;


 attributes a2, b2 are strings;
 method getA1(), getA2(), getB1(), getB2() returns a1, a2, b1, and b2, respectively.

 NOT YET ANSWERED


5. How does inheritance contribute to software reusability?
Object-oriented programming languages that offer inheritance enable reuse of old code in new
applications. By enabling a developer to specify new code in terms of pre-existing code and new
extensions, it does this. The potential for such reuse to boost productivity is a considerable
advantage.

6. Given the following class hierarchy diagram, which class’s printLine() method would be used for
each of the messages below (assuming z is an object instantiated from class F):
 NOT YET ANSWERED

7.What can you say about the method printLine(String x) of class G in Question 6?
 NOT YET ANSWERED

8.Distinguish between contract inheritance and implementation inheritance.


Contract Inheritance: Derived contracts have access to all non-private members, including internal
methods and state variables. However, employing this is prohibited. Function overriding is permitted
as long as the function signature stays the same.

Implementation Inheritance is a method by which a base class's code is reused by a subclass. By


default, the subclass keeps all of the base class's operations, but it can override some or all of them,
substituting its own implementation for that of the base class.

9.Discuss the problem associated with multiple inheritance. How does Java overcome it and what
feature is provided in Java to achieve multiple inheritance? Discuss the limitation of this feature.

Due to two factors, Java does not support multiple inheritance. First, every class in Java is a
descendant of the Object class. A subclass has the potential to inherit from more than one
superclass, giving it the ability to do so. Every class in Java has a constructor, whether it is explicitly
written or not.

10.An abstract class contains one or more abstracted methods. (Fill in the blank.) Distinguish
between an abstract class and an interface. Which is better and why?

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods. Since
abstract methods. Java 8, it can have default and static methods
also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.

6) An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java interfaces. only.
7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".

8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.

9)Example: Example:

public abstract class Shape{  public interface Drawable{

public abstract void draw();  void draw();

} }

 Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves
fully abstraction (100%).
11.What is the expected output for the code in listing 6-7.
interface I {
void x();

void y(); }

class A implements I {

A() {}

public void w() {System.out.println("in A.w");}

public void x() {System.out.println("in A.x");}

public void y() {System.out.println("in A.y");} }

class B extends A {

B() {}

public void y() {

System.out.println("in B.y"); }

void z() {

w();

x(); }

static public void main(String args[]) {

A aa = new A();

B bb = new B();

bb.z();

bb.y(); } }
PROGRAMS
Module 6
Test drive for cylinder class Testcylinder.java
* A test driver for the Cylinder class.
*/
public class TestCylinder {
   public static void main(String[] args) {
      Cylinder cy1 = new Cylinder();
      //Construced a Circle with Circle()
      //Constructed a Cylinder with Cylinder()
      System.out.println("Radius is " + cy1.getRadius()
         + ", Height is " + cy1.getHeight()
         + ", Color is " + cy1.getColor()
         + ", Base area is " + cy1.getArea()
         + ", Volume is " + cy1.getVolume());
      //Radius is 1.0, Height is 1.0, Color is red,
      //Base area is 3.141592653589793, Volume is 3.141592653589793

      Cylinder cy2 = new Cylinder(5.0, 2.0);


      //Construced a Circle with Circle(radius)
      //Constructed a Cylinder with Cylinder(height, radius)
      System.out.println("Radius is " + cy2.getRadius()
         + ", Height is " + cy2.getHeight()
         + ", Color is " + cy2.getColor()
         + ", Base area is " + cy2.getArea()
         + ", Volume is " + cy2.getVolume());
      //Radius is 2.0, Height is 5.0, Color is red,
      //Base area is 12.566370614359172, Volume is 62.83185307179586
   }
}
Test driver Test person.java
/**
* A test driver for Person and its subclasses.
*/
public class TestPerson {
   public static void main(String[] args) {
      /* Test Student class */
      Student s1 = new Student("Tan Ah Teck", "1 Happy Ave");
      s1.addCourseGrade("IM101", 97);
      s1.addCourseGrade("IM102", 68);
      s1.printGrades();
      //Student: Tan Ah Teck(1 Happy Ave) IM101:97 IM102:68
      System.out.println("Average is " + s1.getAverageGrade());
      //Average is 82.5

      /* Test Teacher class */


      Teacher t1 = new Teacher("Paul Tan", "8 sunset way");
      System.out.println(t1);
      //Teacher: Paul Tan(8 sunset way)
      String[] courses = {"IM101", "IM102", "IM101"};
      for (String course: courses) {
         if (t1.addCourse(course)) {
            System.out.println(course + " added");
         } else {
            System.out.println(course + " cannot be added");
         }
      }
      //IM101 added
      //IM102 added
      //IM101 cannot be added
      for (String course: courses) {
         if (t1.removeCourse(course)) {
            System.out.println(course + " removed");
         } else {
            System.out.println(course + " cannot be removed");
         }
      }
      //IM101 removed
      //IM102 removed
      //IM101 cannot be removed
   }
Circle.java
public class Circle {
   // private instance variables
   private double radius;
   private String color;

   // Constructors
   public Circle() {
      this.radius = 1.0;
      this.color = "red";
      System.out.println("Construced a Circle with Circle()");  // for
debugging
   }
   public Circle(double radius) {
      this.radius = radius;
      this.color = "red";
      System.out.println("Construced a Circle with Circle(radius)");  //
for debugging
   }
   public Circle(double radius, String color) {
      this.radius = radius;
      this.color = color;
      System.out.println("Construced a Circle with Circle(radius,
color)");  // for debugging
   }

   // public getters and setters for the private variables


   public double getRadius() {
      return this.radius;
   }
   public String getColor() {
      return this.color;
   }
   public void setRadius(double radius) {
      this.radius = radius;
   }
   public void setColor(String color) {
      this.color = color;
   }

   /** Returns a self-descriptive String */


   public String toString() {
      return "Circle[radius=" + radius + ",color=" + color + "]";
   }
   /** Returns the area of this Circle */
   public double getArea() {
      return radius * radius * Math.PI;
   }
}
Cylinder.java
/**
* A Cylinder is a Circle plus a height.
*/
public class Cylinder extends Circle {
   // private instance variable
   private double height;

   // Constructors
   public Cylinder() {
      super();  // invoke superclass' constructor Circle()
      this.height = 1.0;
      System.out.println("Constructed a Cylinder with Cylinder()");  //
for debugging
   }
   public Cylinder(double height) {
      super();  // invoke superclass' constructor Circle()
      this.height = height;
      System.out.println("Constructed a Cylinder with
Cylinder(height)");  // for debugging
   }
   public Cylinder(double height, double radius) {
      super(radius);  // invoke superclass' constructor Circle(radius)
      this.height = height;
      System.out.println("Constructed a Cylinder with Cylinder(height,
radius)");  // for debugging
   }
   public Cylinder(double height, double radius, String color) {
      super(radius, color);  // invoke superclass' constructor
Circle(radius, color)
      this.height = height;
      System.out.println("Constructed a Cylinder with Cylinder(height,
radius, color)");  // for debugging
   }

   // Getter and Setter


   public double getHeight() {
      return this.height;
   }
   public void setHeight(double height) {
      this.height = height;
   }

   /** Returns the volume of this Cylinder */


   public double getVolume() {
      return getArea()*height;   // Use Circle's getArea()
   }

   /** Returns a self-descriptive String */


   public String toString() {
      return "This is a Cylinder";  // to be refined later
   }
}
The subclass student.java
/**
* The Student class, subclass of Person.
*/
public class Student extends Person {
   // private instance variables
   private int numCourses;   // number of courses taken so far
   private String[] courses; // course codes
   private int[] grades;     // grade for the corresponding course codes
   private static final int MAX_COURSES = 30; // maximum number of
courses

   /** Constructs a Student instance with the given name and address */
   public Student(String name, String address) {
      super(name, address);
      numCourses = 0;
      courses = new String[MAX_COURSES];
      grades = new int[MAX_COURSES];
   }

   /** Returns a self-descriptive string */


   @Override
   public String toString() {
      return "Student: " + super.toString();
   }

   /** Adds a course and its grade - No input validation */


   public void addCourseGrade(String course, int grade) {
      courses[numCourses] = course;
      grades[numCourses] = grade;
      ++numCourses;
   }

   /** Prints all courses taken and their grade */


   public void printGrades() {
      System.out.print(this);
      for (int i = 0; i < numCourses; ++i) {
         System.out.print(" " + courses[i] + ":" + grades[i]);
      }
      System.out.println();
   }

   /** Computes the average grade */


   public double getAverageGrade() {
      int sum = 0;
      for (int i = 0; i < numCourses; i++ ) {
         sum += grades[i];
      }
      return (double)sum/numCourses;
   }
}
The subclass teacher.java

/**
* The Teacher class, subclass of Person.
*/
public class Teacher extends Person {
   // private instance variables
   private int numCourses;   // number of courses taught currently
   private String[] courses; // course codes
   private static final int MAX_COURSES = 5; // maximum courses
   /** Constructs a Teacher instance with the given name and address */
   public Teacher(String name, String address) {
      super(name, address);
      numCourses = 0;
      courses = new String[MAX_COURSES];
   }

   /** Returns a self-descriptive string */


   @Override
   public String toString() {
      return "Teacher: " + super.toString();
   }

   /** Adds a course. Returns false if the course has already existed */
   public boolean addCourse(String course) {
      // Check if the course already in the course list
      for (int i = 0; i < numCourses; i++) {
         if (courses[i].equals(course)) return false;
      }
      courses[numCourses] = course;
      numCourses++;
      return true;
   }

   /** Removes a course. Returns false if the course cannot be found in the course list */
   public boolean removeCourse(String course) {
      boolean found = false;
      // Look for the course index
      int courseIndex = -1;  // need to initialize
      for (int i = 0; i < numCourses; i++) {
         if (courses[i].equals(course)) {
            courseIndex = i;
            found = true;
            break;
         }
      }
      if (found) {
         // Remove the course and re-arrange for courses array
         for (int i = courseIndex; i < numCourses-1; i++) {
            courses[i] = courses[i+1];
         }
         numCourses--;
         return true;
      } else {
         return false;
      }
   }
}

The subclass person.java

/**
* The superclass Person has name and address.
*/
public class Person {
   // private instance variables
   private String name, address;

   /** Constructs a Person instance with the given name and address */
   public Person(String name, String address) {
      this.name = name;
      this.address = address;
   }

   // Getters and Setters


   /** Returns the name */
   public String getName() {
      return name;
   }
   /** Returns the address */
   public String getAddress() {
      return address;
   }
   /** Sets the address */
   public void setAddress(String address) {
      this.address = address;
   }

   /** Returns a self-descriptive string */


   @Override
   public String toString() {
      return name + "(" + address + ")";
   }
}

You might also like