In: Computer Science
7. What are abstract classes and interfaces in Java? What are they used for, and what are they comprised of? Clearly explain the difference between the two.
Abstract classes in Java
Synatax: abstract class classname{}
AbstractMethod
Syntax:
Public abstract returntype methodname();
Example
abstract class Abex{
public void NM(){
System.out.println("Normal method");
}
abstract public void AM();
}
class example extends Abex
public void AM()
{
System.out.println("Implementing Abstarct method in subclass");
}
public static void main(String args[])
{
example obj = new example();
obj.AM();
}
}
Output : Implementing Abstarct method in subclass
Interface in Java
Syntax interface
interface-name{
void m1();
void m2();
}
Purpose
Example
interface Inter
{
public void m1();
public void m2();
}
class sam implements Inter
{
public void m1()
{
system.out.println("implementation of m1");
}
public void m2()
{
system.out.println("implementation of m2");
}
public static void main(String args[])
{
Inter obj = new sam();
obj.m2();
}
}
Output: implementation of m2
Difference between the two
Abstract Class | Interface |
It can have both abstract methods and normal methods | By default all methods here are abstract |
It can be declared by using keyword abstract | It can be declared by using keyword interface |
It can have final,static,non-final,non-static variables | it can only have final and static variables |
A class can extend only one abstract class | An class can implements by any number of inerfaces |