August 2000
JP219 : JAVA PROGRAMMING

QUESTION 5

Total Marks: 15 Marks

Click here to access other questions

SUGGESTED SOLUTIONS
Solutions and allocated marks are indicated in green.
Return to
Question 5

(a) Explain what is meant by an abstract method in Java. [1 mark]
(a) An abstract method is one for which there is a signature, but no implementation in the class. [1 mark]

(b) Explain what is meant by an abstract class, and how it may relate to abstract methods. [2 marks]
(b) • An abstract class is one which is not fully implemented, and therefore cannot be instantiated; (1 mark)
• Any class which contains abstract methods is an abstract class; (1 mark)
[2 marks]

(c) Write the abstract class Shape, such that it contains two public abstract methods, area and circumference, both of which are declared to return a double and take no parameters, and a member a, which is of type double, and can be inherited by any subsequent derived classes. [3 marks]
(c) public abstract class Shape {
  protected double a;
  public abstract double area();
  public abstract double circumference();
};
• Declaring the class to be abstract; (1 mark)
• Declaring a to be a protected double; (1 mark)
• Declaring both methods to be public abstract; (1 mark)
[3 marks]

(d) Implement the public class Rectangle, such that it inherits from the Shape class. Your class should contain the integer members width and height, such that they are not accessible outside the class, and public accessor methods which return their values. [4 marks]
(d) public class Rectangle extends Shape {
  private int width;
  private int height;
  public int width() {return width;}
  public int height() {return height;}
};
• Declaring the class to extend shape; (1 mark)
• Declaring the private ints; (1 mark)
• Implementing the public accessor methods; (1 mark)
• Noting that these should actually be width() and height() and other naming conventions are not necessary; (1 mark)
[4 marks]

(e) Add to your class a constructor function, which has parameters which initialise all the member variables appropriately. [3 marks]
(e) Rectangle(int w, int h, double a) {
  this.width= w;
  this.height= h;
  this.area= a;
}
• Constructor signature, including all three parameters; (1 mark)
• Correctly typing the parameters; (1 mark)
• Initialising the local members with the parameters; (1 mark)
[3 marks]

(f) An inexperienced Java programmer now tries to write a program which attempts to create a Rectangle object. Explain the error he is likely to encounter in doing this, and why. [2 marks]
(f) • He will be unable to instantiate the rectangle class; (1 mark)
• Both area() or circumference() are not yet implemented, therefore the class is implicitly abstract; (1 mark)
[2 marks]