In Java, Shape is declared as `public abstract class Shape` with an abstract method area(). What happens with the statement `Shape s = new Shape();`?
AIt creates a Shape whose area() returns 0
BIt compiles, but calling s.area() throws an exception
CIt does not compile, because an abstract class cannot be instantiated
DIt creates an object of the first subclass of Shape
The abstract keyword tells the compiler that Shape is incomplete, so new Shape() is rejected at compile time. A variable of type Shape is still allowed: Shape s = new Circle(1.0); compiles if Circle is a concrete subclass.
Question 2 Multiple Choice
Circle extends the abstract class Shape but does not provide a body for Shape's abstract method area(), and Circle is not itself marked abstract. What does the Java compiler do?
AIt reports an error, because a concrete class must implement every inherited abstract method
BIt accepts the class and uses an empty area() method
CIt accepts the class and makes area() return 0.0
DIt accepts the class but prevents Circle objects from calling area()
A non-abstract class must provide bodies for all abstract methods it inherits. Circle must either implement area() or be declared abstract itself, in which case its own subclasses must implement it.
Question 3 True / False
A single Java class can implement more than one interface.
TTrue
FFalse
Answer: True
Java allows a class to extend only one superclass, but it can implement many interfaces, for example `class Song implements Comparable<Song>, Serializable`. This is how a class can belong to several unrelated types at once.
Question 4 Short Answer
You are designing classes Dog, Cat and Robot. All three must provide a method makeSound(). Dog and Cat also share name and age fields with identical code. Which tools would you use, and why?
Think about your answer, then reveal below.
Model answer: Put the shared fields and code in an abstract class such as Animal that Dog and Cat extend. Define an interface such as SoundMaker with makeSound(), and have Animal (or Dog and Cat) and Robot implement it. Robot is not an animal, so it should not extend Animal, but it can still share the SoundMaker type.
Abstract classes are a good fit when related classes share state and code in an 'is-a' family. Interfaces are a good fit when unrelated classes need to promise the same capability.