[Solved] CS2030s Problem Set #3

$25

File Name: CS2030s_Problem_Set_#3.zip
File Size: 207.24 KB

SKU: [Solved] CS2030s Problem Set #3 Category: Tag:
5/5 - (1 vote)
  1. Given the following interfaces.

interface Shape { double getArea();

}

interface Printable { void print();

}

  • Suppose class Circle implements both interfaces above. Given the following program fragment,

Circle c = new Circle(new Point(0,0), 10);

Shape s = c;

Printable p = c;

Are the following statements allowed? Why do you think Java does not allow some of the following statements?

  1. print();
  2. print();
  • getArea();iv. p.getArea();
  • Someone proposes to re-implement Shape and Printable as abstract classes instead? Would statements (i) to (iv) be allowed?
  • Now lets define another interface PrintableShape as

public interface PrintableShape extends Printable, Shape {

}

and let class Circle implement PrintableShape instead. Would statements (i) to (iv) be allowed now? Can an interface inherit from multiple parent interfaces?

  1. Suppose Java allows a class to inherit from multple parent classes. Give a concrete example why this could be problematic.

On the other hand, Java does allow classes to implement multiple interfaces. Explain why this isnt problematic.

  1. Consider the following classes: FormattedText that adds formatting information to the text. We call toggleUnderline() to add or remove underlines from the text. A PlainText is a FormattedText that is always NOT underlined.

class FormattedText { private final String text; private final boolean isUnderlined;

FormattedText(String text) { this.text = text; this.isUnderlined = false;

}

/*

* Overloaded constructor, but made private to prevent * clients from calling it directly.

*/ private FormattedText(String text, boolean isUnderlined) { this.text = text;

this.isUnderlined = isUnderlined;

}

FormattedText toggleUnderline() { return new FormattedText(this.text, !this.isUnderlined);

}

@Override public String toString() { if (this.isUnderlined) { return this.text + (underlined);

} else {

return this.text;

}

}

}

class PlainText extends FormattedText {

PlainText(String text) { super(text); // text is NOT underlined

}

@Override

PlainText toggleUnderline() { return this;

}

}

Does the above violate Liskov Substitution Principle? Explain.

  1. Consider the following program.

class A { int x;

A(int x) { this.x = x;

}

  • method() {return new A(x);

}

}

class B extends A {

B(int x) {

super(x);

}

@Override

  • method() {return new B(x);

}

}

Does it compile? What happens if we swap the entire definitions of method() between class A and class B? Does it compile now? Give reasons for your observations.

Reviews

There are no reviews yet.

Only logged in customers who have purchased this product may leave a review.

Shopping Cart
[Solved] CS2030s Problem Set #3
$25