Sie sind auf Seite 1von 14

CSC 8000 HOMEWORK8 – INHERITANCE, INTERFACES

Inheritance and Constructors:

1. Create a constructor for a SavingsAccount class which is a child class of the Account
class. The constructor initializes its parent class’s instance variables - CustName,
AccNumber. It also initializes its own instance variable InterestRate.

2. Create a constructor for an alarm clock class which is a child class of Clock. It initializes
its parent class instance variables – second and minute – and initializes it own instance
variable – a boolean – AlarmOn.

Inheritance and Methods

1.Write the toString method for a child class – alarm clock class as stated above – which
prints out all the data it inherits as well as its own data.

2. Write a print method for the alarm clock class which makes use of its parent class print
method.

3. Consider this code that creates some Location objects with coordinates x=10 and y=20:
Location a, b, c;
a = new Location(10,20);
b = new Location(10,20);
c = b;
a == b ___________________
a.equals(b) _____________________
a==c _____________________
a.equals(c) _____________________
b==c _____________________
b.equals(c) ______________________
After this code executes, what are the values of these boolean expressions?
4.Suppose that the Foo class does not have an equals method. What happens when an
expression x.equals(y); is evaluated for two Foo objects?
o A. The expression is true if x and y refer to the same object
o B. The expression is true if x and y refer to objects with the same values
o C. Compiler error
o D. Run-time error
5. Suppose that the Foo class has a typical equals method. What happens when an
expression x.equals(y); is evaluated for two Foo objects?
o A. The expression is true if x and y refer to the same object
o B. The expression is true if x and y refer to objects with the same values
o C. Compiler error
o D. Run-time error
o
6. Suppose that I have the following declarations:
int[ ] data = new int[100];
int i;
Write a small segment of Java code that will shift data[51]...data[99] down one spot
to the locations data[50]...data[98]. The value of data[99] remains at its original
value. Use a for loop (not System.arraycopy).

1
CSC 8000 HOMEWORK8 – INHERITANCE, INTERFACES

7. The instruction super( ); does which of the following?


a) calls the method super as defined in the current class
b) calls the method super as defined in the current class’ parent class
c) calls the method super as defined in java.lang
d) calls the constructor as defined in the current class
e) calls the constructor as defined in the current class’ parent class

8. Inheritance through an extended class supports which of the following concepts?


a) interfaces
b) modulary
c) information hiding
d) code reuse
e) correctness

9. Aside from permitting inheritance, the visibility modifier protected is also used to
a) permit access to the protected item by any class defined in the same package
b) permit access to the protected item by any static class
c) permit access to the protected item by any parent class
d) ensure that the class can not throw a NullPointerException
e) define abstract elements of an interface

10. Which of the following is an example of multiple inheritance?


a) a computer can be a mainframe or a PC
b) a PC can be a desktop or a laptop
c) a laptop is both a PC and a portable device
d) a portable device is a lightweight device
e) Macintosh and IBM PC are both types of PCs

11. Java does not support multiple inheritance, but some of the abilities of multiple
inheritance are available by
a) importing classes
b) implementing interfaces
c) overriding parent class methods
d) creating aliases
e) using public rather than protected or private modifiers

12. All classes in Java are directly or indirectly subclasses of the _______ class.
a) Wrapper
b) String
c) Reference
d) this
e) Object

13. Which of the following is not a method of the Object class?


a) clone
b) compareTo
c) equals
d) toString
e) all of the above are methods of the Object class

2
CSC 8000 HOMEWORK8 – INHERITANCE, INTERFACES

14. Abstract methods are used when defining


a) interface classes
b) derived classes
c) classes that have no constructor
d) arrays
e) classes that have no methods

15. Which of the following is true regarding Java classes?


a) All classes must have 1 parent but may have any number of children (derived or
extended) classes.
b) All classes must have 1 child (derived or extended) class but may have any number
of parent classes.
c) All classes must have 1 parent class and may have a single child (derived or
extended) class.
d) All classes can have any number (0 or more) of parent classes and any number of
children (derived or extended) classes.
e) All classes can have either 0 or 1 parent class and any number of children (derived
or extended) classes.

16. Two children of the same parent class are known as


a) aliases
b) relatives
c) clones
d) brothers
e) siblings

17. A variable declared to be of one class can later reference an extended class of that
class( become an alias of a child class). This variable is known as
a) protected
b) derivable
c) cloneable
d) polymorphic
e) none of the above, a variable declared to be of one class can never reference any
other type of class, even an extended class

18. In order to determine the type that a polymorphic variable refers to, the decision is
made
a) by the programmer at the time the program is written
b) by the compiler at compile time
c) by the operating system when the program is loaded into memory
d) by the Java run-time environment at run time
e) by the user at run time

For the following questions, assume that Student, Employee and Retired are all extended
classes of Person, and all four classes have different implementations of the method
getMoney. Consider the following code where … are the required parameters for the
constructors:
Person p = new Person(…);
int m1 = p.getMoney( ); // assignment 1
p = new Student(…);
int m2 = p.getMoney( ); // assignment 2

3
CSC 8000 HOMEWORK8 – INHERITANCE, INTERFACES

if (m2 < 100000) p = new Employee(…);


else if (m1 > 50000) p = new Retired(…);
int m3 = p.getMoney( ); // assignment 3

19. The reference to getMoney( ) in assignment 1 is to the class


a) Person
b) Student
c) Employee
d) Retired
e) none of the above, this cannot be determined by examining the code

20. The reference to getMoney( ) in assignment 2 is to the class


a) Person
b) Student
c) Employee
d) Retired
e) none of the above, this cannot be determined by examining the code

21) The reference to getMoney( ) in assignment 3 is to the class


a) Person
b) Student
c) Employee
d) Retired
e) none of the above, this cannot be determined by examining the code

22) The relationship between a parent class and a child class is referred to as a(n) ____
relationship.
a) has-a
b) is-a
c) was-a
d) instance-of
e) alias

23. If s is a String, and s = “no”; is performed, then s


a) stores the String “no”
b) references the memory location where “no” is stored
c) stores the characters ‘n’, ‘o’
d) stores an int value that represents the two characters
e) stores the character ‘n’ and a reference to the memory location where the next
character, ‘o’ is stored

24. Assume that you are defining a class and you want to implement an ActionListener. You
state addActionListener(this); in your class’ constructor. What does this mean?
a) The class must import another class which implements ActionListener
b) The class must define the method actionPerformed
c) The class must define the method ActionListener
d) The class must define an inner class called ActionListener
e) The class must define the method actionPerformed in an inner class named
ActionListener

4
CSC 8000 HOMEWORK8 – INHERITANCE, INTERFACES

25. Which of the following is true regarding outer and inner classes?
a) no method of an inner class can be static
b) no method of an outer class can be static
c) no instance data or method of an inner class can be static
d) no instance data or method of an outer class can be static
e) none of the above, there is no restriction on what can and cannot be static between
inner and outer classes

26. A listener is an object that


a) implements any type of interface
b) is used to accept any form of input
c) is an inner class to a class that has abstract methods
d) waits for some action from the user
e) uses the InputStreamReader class

/*****************************************************************************
True/False Questions

1.____Interface classes cannot be extended but classes that implement interfaces can be
extended.
2.____A derived class has access to all of the methods of the parent class, but only the
protected or public instance data of the parent class.
3.___If class AParentClass has a protected instance data x, and AChildClass is a derived
class of AParentClass, then AChildClass can access x but can not redefine x to be a different
type.

Consider the following class hierarchy and answer questions 4-6

Y Z

A B

4._____A is a derived class of X.


5.____Y is a derived class of Z.
6.___If A, B, Y and Z all contain the same instance data d1, then d1 should be declared in X
and inherited into Y, Z, A and B.

7. Which of these function calls will cause an exception to be thrown when x is 42. (x is an
int variable).

5
CSC 8000 HOMEWORK8 – INHERITANCE, INTERFACES

a.
if (0 < x)
throw new IllegalArgumentException("Bad x");
B. if (0 == x)
throw new IllegalArgumentException("Bad x");
a.
if (0 > x)
throw new IllegalArgumentException("Bad x");

c. None of the above will cause an exception when x is 42.

8. __Will the following compile – is it an narrowing or a widening conversion.


String s = “Objection”;
Object obj;
Obj = s;
s = obj; _______________________________

9. In order to implement Comparable in a class, what method(s) must be defined in that


class?
f) equals
g) compares
h) both lessThan and greaterThan
i) compareTo
j) both compares and equals
k)
/************************************************************************
For questions 11, consider a class called ChessPiece. This class has two instance data, String
type and int player. The variable type will store “King”, “Queen”, “Bishop”, etc and the int
player will store 0 or 1 depending on whose piece it is. We wish to implement Comparable
for the ChessPiece class. Assume that, the current ChessPiece is compared to a ChessPiece
passed as a parameter. Pieces are ordered as follows: “Pawn” is a lesser piece to a
“Knight” and a “Bishop”, “Knight” and “Bishop” are equivalent for this example, both are
lesser pieces to a “Rook” which is a lesser piece to a “Queen” which is a lesser piece to a
“King.”

10. Which of the following pieces of logic could be used in the method that implements
Comparable? Assume that the method is passed Object a, which is really a ChessPiece.
Also assume that ChessPiece has a method called returnType which returns the type of the
given piece. Only one of these answers has correct logic.
l) if (this.type < a.returnType( )) return –1;
m) if (this.type = = a.returnType( )) return 0;
n) if (this.type.equals(a.returnType( )) return 0;
o) if (a.returnType( ).equals(“King”)) return -1;
p) if (a.returnType( ).equals(“Pawn”)) return 1;
/*********************************************************************
Free Form
1.Explain the difference between implementing an interface and a derived class.

2.Explain the difference between using an imported class and extending a class.

6
CSC 8000 HOMEWORK8 – INHERITANCE, INTERFACES

3.Assume the class Student implements the Speaker interface from the textbook. Recall
that this interface includes two abstract methods, speak( ) and announce(String str).
A Student contains one instance data, String classRank. Write the Student class so that it
implements Speaker as follows. The speak method will output “I am a newbie here” if the
Student is a “Freshman”, “I hate school” if the Student is either a “Sophomore” or a
“Junior”, or “I can not wait to graduate” if the student is a “Senior”. The announce
method will output “I am a Student, here is what I have to say” followed by the String
parameter on a separate line. Finally, the classRank is initialized in the constructor. Only
implement the constructor and the methods to implement the Speaker interface.

4.Consider a class Name, which has four instance data (all Strings): first, middle, last and
title. Even though Name inherits the equal method from Object, it would make more sense
to override it. Why?

5.Explain what a NullPointerException is and how it can arise.

6.Consider the condition (x = = y). How is this handled if x and y are primitive types? How
is this handled if x and y are objects?

7. Assume a class Foo implements Comparable. Without knowing anything else about the
Foo class, write an equal method that returns true if the Foo parameter passed to this Foo is
equal to this Foo as determined by using the implementation of Comparable.

Polymorphic Objects

1.___Given the Philosopher, Speaker example from the Interface lecture – available on my
website – which of the following are true:
a) All philosophers can speak and announce and pontificate but dogs can only speak.
b) All dogs are speakers but not all speakers are dogs.
c) An interface name can be used to declare a reference variable. It can then be used
to refer to all classes that implement the interface.
d) In class talking, the variable current is initially set to a new dog object. Then current
is assigned to a Philosopher object which is also valid because a philosopher can be a
dog.
e) This action is not possible with regular object references. You cannot assign an
object reference of one class to another class.

2. _____Method Name Conflicts - A class implements two interfaces that each have a
method with the same name Square():

Which of the following is true:

a)If both Square() methods have different signatures, then the class implements two
overloaded methods.

b)If both methods have the same signature and the same return type, then the class
implements one square method to satisfy both.

c) If both Square() methods have the same signature and different return types, then the
class can implement both interfaces.

7
CSC 8000 HOMEWORK8 – INHERITANCE, INTERFACES

Some more inheritance problems

Some more Inheritance Problems


Multiple Choice
1. Which of the following classes cannot be extended?
a.
class A
{}

b.
class A
{
private A();
}
c.
final class A
{}

d.
class A
{
protected A();
}

2. What modifier should you use on the members of a class so that a class in the same
package can access them but a class in a different package cannot access them?
a. public
b. private
c. protected
d. Use the default modifier.
3. What modifier should you use so that a class in a different package cannot access the
members of class, but its subclasses in any package can access it?
a. public
b. private
c. protected
d. Use the default modifier.

4. What is the output of running class C?


class A
{
public A()
{
System.out.println(
"The default constructor of A is invoked");
}
}
class B extends A
{
public B()
{

8
CSC 8000 HOMEWORK8 – INHERITANCE, INTERFACES

System.out.println(
"The default constructor of B is invoked");
}
}
public class C
{
public static void main(String[] args)
{
B b = new B();
}
}
a. none
b. "The default constructor of B is invoked"
c. "The default constructor of A is invoked"
"The default constructor of B is invoked"
d. "The default constructor of B is invoked"
"The default constructor of A is invoked"
e. "The default constructor of A is invoked"

5. Which declares an abstract method in an abstract Java class?


a. public abstract method();
b. public abstract void method();
c. public void abstract Method();
d. public void method() {}
e. public abstract void method() {}

6. Consider the following classes:


public class Parent{

public void foo() {


System.out.println( "Parent foo" );
bar();
}

public void bar(){


System.out.println( "Parent bar" );
}
}

public class ChildFoo extends Parent{

public void foo(){


System.out.println( "ChildFoo foo" );
bar();
}
}

public class ChildBar extends Parent{

public void bar(){


System.out.println( "ChildBar bar" );

9
CSC 8000 HOMEWORK8 – INHERITANCE, INTERFACES

}
}

What is the Output Here?

public class Test{

public static void main(String[] args) {


Parent test = new ChildFoo();
test.foo();
test = new ChildBar();
test.foo();
}
_________________________________________________________

7. Consider the following code:


class Circle
{
public Circle(double r) { }
}
class Cylinder extends Circle
{
double length;
}
public Cylinder(double radius)
{
super(radius);
}
}

Analyze the following code based on the above code(Cylinder is a child of Circle):
Cylinder cy = new Cylinder(2.5);
Circle c = cy;
a. The code has a syntax error.
b. The code has a runtime error.
c. the code compiles but does not run
d. The code is fine, compiles and runs

8. Consider the following classes


public class Test extends A
{
public static void main(String[] args)
{
Test t = new Test();
t.print();
}
}

class A

10
CSC 8000 HOMEWORK8 – INHERITANCE, INTERFACES

{
String s;

public A(String s)
{
this.s = s;
}
public void print()
{
System.out.println(s);
}
}
a. The program does not compile because Test does not have a constructor Test().
b. The program would compile if the constructor in the class A were removed.
c. The program compiles, but it has a runtime error due to the conflict on the method name
print.
d. The program runs just fine.

9. Consider the following classes


class C1 {};
class C2 extends C1 {};
class C3 extends C1 {};
C2 c2 = new C2();
C3 c3 = new C3();

Analyze the following statement:


c2 = (C2)((C1)c3);

a. c3 is cast into c2 successfully.


b. You will get a runtime error because you cannot cast objects from sibling classes.
c. You will get a runtime error because the Java runtime system cannot perform multiple
casting in nested form.
d. The statement is correct.
10. Show the output of running the class Test in the following code lines:
interface A
{
public void print();
}

class C {}

class B extends C implements A


{
public void print() { }
}

public class Test extends Thread


{
public static void main(String[] args)
{

11
CSC 8000 HOMEWORK8 – INHERITANCE, INTERFACES

B b = new B();
if (b instanceof A)
System.out.println("b is an instance of A");
if (b instanceof C)
System.out.println("b is an instance of C");
}
}
a. Nothing.
b. b is an instance of A.
c. b is an instance of C.
d. b is an instance of A followed by b is an instance of C.

11. Which of the following class definitions defines a legal abstract class?
a.
class A
{
abstract void unfinished()
}
b.
class A
{
abstract void unfinished();
}

c.
abstract class A
{
abstract void unfinished();
}
d.
public class abstract A
{
abstract void unfinished();
}

12. Which is the advantage of encapsulation?


a. Only public methods are needed.
b. No exceptions need to be thrown from any method.
c. Making the class final causes no consequential changes to other code.
d. The implementation of the methods in the class can change without changing the
interface and causes no consequential changes to other code.
e. You can change the interface without changing the implementation and causes no
consequential changes to other code.

13. Which statement is true about a non-static inner class?


a. It must implement an interface.
b. It is accessible from any other class.
c. It can only be instantiated in the enclosing class.
d. It must be final if it is declared in a method scope.

12
CSC 8000 HOMEWORK8 – INHERITANCE, INTERFACES

e. It can access private instance variables in the enclosing object.

14. Analyze the following code:

public class Test1


{
public Object max(Object o1, Object o2)
{
if ((Comparable)o1.compareTo(o2) >= 0)
{
return o1;
}
else
{
return o2;
}
}
}
a. The program has a syntax error because Test1 does not have a main method.
b. The program has a syntax error because o1 is an Object instance and it does not have the
compareTo method.
c. The program has a syntax error because you cannot cast an Object instance o1 into
Comparable.
d. The program would compile if ((Comparable)o1.compareTo(o2) >= 0) is replaced by
(((Comparable)o1.)compareTo(o2) >= 0).
e. b and d are both correct.

15.Given the following inheritance structure:

fruit

Apple
Orange

GoldenDelicious MacIntosh

Assume the following declarations:

Fruit fruit = new GoldenDelicious();


Orange orange = new Orange();

Answer the following questions:

 Is fruit instanceof Orange true


 Is fruit instanceof Apple true

13
CSC 8000 HOMEWORK8 – INHERITANCE, INTERFACES

 Is orange instanceof Fruit true


 Is fruit instanceof MacIntosh true

14

Das könnte Ihnen auch gefallen