Java LAB 11
Java LAB 11
LAB # 11
OBJECTIVE:
To study Abstract classes, Interface and final keyword.
THEORY:
abstract class A
{
abstract void add()
{ //Abstract method with body will generate error
System.out.println("Add of A");
}
void mull()
{
System.out.println("Multiply of A");
}
void div()
{
System.out.println("Divide of A\n");
}
}
obj1.add(); //Add of B
obj1.sub(); //Subtract of C
obj1.mull(); //Multiply of C
obj1.div(); //Divide of B
obj2.add(); //Add of B
obj2.sub(); //Subtract of C
obj2.mull(); //Multiply of C
obj2.div(); //Divide of B
obj3.add(); //Add of B
obj3.sub(); //Subtract of C
obj3.mull(); //Multiply of C
obj3.div(); //Divide of B
}
}
OUTPUT
10.2 INTERFACES
Using the keyword interface, you can fully abstract a class’ interface from its
implementation. That is, using interface, you can specify what a class must
do, but not how it does it. Interfaces are syntactically similar to classes, but
they lack instance variables, and their methods are declared without any
body. In practice, this means that you can define interfaces which don’t make
assumptions about how they are implemented. Once it is defined, any number
of classes can implement an interface. Also, one class can implement any
number of interfaces.
Program 1: Interface1
Interface X
(Abstract add and sub)
Class A Implements X
(Implements add and sub)
interface X{
void add();
void sub();
}
class A implements X{
public void add(){
System.out.println("Add of A");
}
public void sub(){
System.out.println("Subtract of A");
}
}
obj1.add ();
obj1.sub ();
System.out.println("\add and Subtract of A on Interface
reference\n");
obj2.add ();
obj2.sub ();
}
}
OUTPUT
Any class derived from PolyLine would not be able to redefine this method.
Obviously, an abstract method cannot be declared as final — because it must be
defined in a subclass somewhere. If you declare a class as final, you prevent any
subclasses from being derived from it. To declare the class PolyLine as final, you
would define it as:
If you now attempt to define a class based on PolyLine, you will get an error message
from the compiler. An abstract class cannot be declared as final since this would
prevent the abstract methods in the class from ever being defined. Declaring a class as
final is a drastic step that prevents the functionality of the class being extended by
derivation, so you should be very sure that you want to do this.
LAB TASK
Interface Y
(Abstract mull)
Interface X Extends Y
(Abstract add and sub)
Class A Implements X
(Implements add, sub and mull)
2. Create an Interface Shape with three child classes Circle, Square and
Rectangle. Create a method Draw in each class. Create an Object of
each class that can call the method Draw and it will call automatically
the Draw method of each class. The text of Draw method e.g. Circle is
"This is a Circle".