Questions On Java Object inheritance


Q Can a class have more than one superclass so that it inherits additional methods and behavior?

A
It is possible with some object-oriented programming languages but not Java. One of the goals when Java was developed was to provide a simpler language than an object-oriented language such as C++, and limiting inheritance to a single superclass was one way to acheive this. You can use a special type of class called an interface to inherit behavior that isn't received from superclasses.

Q Most Java programs created up to this point have not used extends to inherit from a superclass. Does this mean they exist outside of the class hierarchy?

A
All classes that you create in Java are part of the hierarchy because the default superclass for the programs you write is
Object. The equals() and toString() methods are part of the behavior that automatically is inherited from Object.

Q When is the full name of a class, such as java.applet.Applet, needed in an extends clause instead of a shorter name such as Applet?

A
You must use the full name whenever you don't use an
import java.applet.Applet; or import.java.applet.*; statement at the beginning of your program. The import statement is used solely to make it easier to refer to class names in programs. Each class of objects in Java has a full name that identifies the group of classes it belongs to. For instance, the Math class is part of the java.lang group of classes. A group of classes is also called a package.
Quiz
To determine what kind of knowledge you inherited from the past hour's work, answer the following questions.
Questions
1. If a superclass handles a method in a way you don't want to use in the subclass, what can you do?

(a) Delete the method in the superclass.
(b) Override the method in the subclass.
(c) Write a nasty letter to the editor of the San Jose Mercury News hoping that Java's developers will read it.
2. Which of the following is not a superclass of
Applet?

(a)
Dialog
(b)
Container
(c)
Component

3.
What statement can you use to refer to the methods and variables of a superclass?

(a)
this
(b)
call
(c) super
Answers
1. b. Because you can override the method, you don't have to change any aspect of the superclass or the way it works.

2.
a.
Dialog has some common superclasses with Applet, but it isn't a superclass, so Applet does not inherit any behavior or attributes from it.

3.
c. A
this statement refers to the current object, and super refers to the superclass.

Post a Comment

أحدث أقدم