107.
108.
There are often programming situations
when you want to create
a super–class that is shared by a number of sub–classes. You
may want to put some common code in the super class but leave
it to the individual classes to provide the specific details. Abstract
classes are useful in such scenarios. So,
you can create an
abstract super–class. You can have concrete methods that
implement the common functionality and abstract methods for the
functionality that is sub–class specific. The sub–classes can then
extend the abstract class and provide
implementation for the
abstract methods.
Explain what is the issue with the following code snippet:
public abstract final class MyAbstractClass {
public void doSomething() {
}
}
Answer:
The above code snippet is not valid. This code declares a class
called MyAbstractClass that has both the abstract as well as
final keyword. An abstract class cannot be final and vice versa.
This is because an abstract class needs to have a sub–class that
implements the abstract methods in the class.
Final is the
opposite of abstract, a class marked as final cannot be
overridden.
Is the following code snippet valid? Explain the reasons
either ways.
public interface ShapeDrawer {
public void draw();
}
109.
public class Triangle implements ShapeDrawer
{
public void draw () {
// code to draw shape
}
public static void main(String args[]) {
ShapeDrawer shapeDrawer = new Triangle(); //Line 1
shapeDrawer.draw(); //Line 2
}
}
Answer:
The above code is valid. This code declares an interface called
ShapeDrawer and a class Triangle that implements this
interface. Line 1 declares a variable
of type ShapeDrawer and
assigns it an object of type Triangle. This is valid, you can
assign an object of a class that
implements an interface to a
variable of the interface type. Line 2 then invokes the draw
method. This executes the code in the draw method in the
Triangle class.
Do'stlaringiz bilan baham: