what is the use of abstract class and interface with example?

Answer Posted / ravi

Abstract classes cannot be instantiated; they must be
subclassed, and actual implementations must be provided for
the abstract methods. Any implementation specified can, of
course, be overridden by additional subclasses. An object
must have an implementation for all of its methods. You
need to create a subclass that provides an implementation
for the abstract method.
for exapmple:
abstract class Shape {

public String color;
public Shape() {
}
public void setColor(String c) {
color = c;
}
public String getColor() {
return color;
}
abstract public double area();
}
public class Point extends Shape {

static int x, y;
public Point() {
x = 0;
y = 0;
}
public double area() {
return 0;
}
public double perimeter() {
return 0;
}
public static void print() {
System.out.println("point: " + x + "," + y);
}
public static void main(String args[]) {
Point p = new Point();
p.print();
}
}
Interface:
In Java, this multiple inheritance problem is solved with a
powerful construct called interfaces. Interface can be used
to define a generic template and then one or more abstract
classes to define partial implementations of the interface.
Interfaces just specify the method declaration (implicitly
public and abstract) and can only contain fields (which are
implicitly public static final). Interface definition
begins with a keyword interface. An interface like that of
an abstract class cannot be instantiated
for example:
interface Shape {

public double area();
public double volume();
}
public class Point implements Shape {

static int x, y;
public Point() {
x = 0;
y = 0;
}
public double area() {
return 0;
}
public double volume() {
return 0;
}
public static void print() {
System.out.println("point: " + x + "," + y);
}
public static void main(String args[]) {
Point p = new Point();
p.print();
}
}

Is This Answer Correct ?    10 Yes 7 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

How do you sort a set in java?

518


What is an inner class in java?

523


what is the difference between thread and runnable types? : Java thread

547


What are the main differences between notify and notifyAll in Java?

583


How to convert string to byte array and vice versa?

583






What is the major drawback of internal iteration over external iteration?

586


Can we define package statement after import statement in java?

557


Can we use synchronized block for primitives?

602


What is factor r?

521


Are there structures in java?

552


In case of inheritance what is the execution order of constructor and destructor?

635


Why array is used in java?

514


What is the difference between throw and throws in java?

554


Why java is object oriented?

585


How variables are declared?

517