CPSC 124, Fall 2017: Sample Answers to Quiz #6

These are sample answers only. Often, answers that are less
detailed than the ones given here can still receive full credit.

Question 1. What is this (in the context of Java classes and objects)?

Answer. "this" is a special variable in Java, which does not have to be declared. Java makes it available automatically. It can be used in instance methods, and it holds a reference to the object that contains the method (or, in terms of messages, the object that received the message that is being processed). It provides a way to refer to "this object." If x is an instance variable, it can also be referred to as this.x within the same class. If doSomething() is an instance method, it can also be called as this.doSomething() within the same class.

Question 2. Explain the concept of inheritance in object-oriented programming. What does it mean to say that a subclass inherits from its superclass?

Answer. In object oriented programming, one class can be defined as a subclass of another class (which is then the superclass of the new class). This is done by saying, for example, class ClassA extends ClassB {...}; here, ClassA is being defined as a subclass of classB. The subclass then inherits all the variables and methods that were defined in the superclass (except for private methods). Those variables and methods become part of the subclass, just as if their definitions were re-typed in the subclass. The subclass can then add new variables and methods to the ones that it inherits from its superclass. It can also replace, or "override", inherited methods with new versions.

Question 3. Consider the following class definition, which could be a legal Java class:

     public class BorderedRect extends Rectangle {    
          public void draw( Graphics g ) {    
              super.draw( g );    
              g.setColor( Color.BLACK );    
              g.drawRect( x, y, width, height );    
          }         
     }     

Answer the following questions about this class. (You do not need to understand the purpose of the class to answer the questions.)

(a) In the first line, what does extends Rectangle mean?

(b) What does the computer do when it executes the line super.draw(g)? (Where is the code that is executed?)

(c) The variables x, y, width, and height are not defined in class BorderedRect. Where are they defined?

Answer. (a) The phrase "extends Rectangle" makes BorderedRect a subclass of Rectangle. This means BorderedRect will inherit everything that is defined in Rectangle.

(b) The method call super.draw(g) calls a method named draw that is defined in the superclass, Rectangle. That method must be defined in class Rectangle for this method call to be legal.

(c) For the references to x, y, width, and height to be legal, Those variables must be defined in the superclass, Rectangle. As long as they are defined in that class, they are inherited by class BorderedRect and can be used there.