Chapter 6
Chapter 6
Abstract Classes
A class which cannot be instantiated is known as abstract class. In
other words –you are not allowed to create object of Abstract class.
Abstract class declaration
Abstract vs Concrete
A class which is not abstract is referred as Concrete class.
Abstract methods
Apart from having abstract class you can have abstract methods as well.
Syntax of abstract method:
public abstract void display();
Points to remember about abstract method:
1) Abstract method has no body.
2) Always end the declaration with a semicolon(;).
3) It must be overridden.
• An abstract class must be extended and in a same wayabstract
method must be overridden.
4) Abstract method must be in a abstract class.
Note: The class which is extending abstract class must override (or
implement) all theabstract methods.
I
Example of Abstract class and method
abstract class Demo1
{
public void disp1(){
System.out.println("Concrete method of abstract class");
}
Output:
I'm overriding abstract method
II
Interface in JAVA
Declaration
interface MyInterface
{
//All the methods are public abstract by default
public void method1();
public void method2();
}
III
Key points:
7. Inside any implementation class, you cannot change the variables declared in
interface because by default, they are public, static and final.
IV
Class Sample implements Try
{
public static void main(String arg[])
{
x=20; //compile time error
}
}
8. Any interface can extend any other interface but cannot implement it. Class
implements interface and interface extends interface.
9. A class can implements any number of interfaces.
10. If there are having two or more same methods in two interfaces and a
class implements both interfaces, implementation of one method is enough.
interface A
{
public void aaa();
}
interface B
{
public void aaa();
}
class Central implements A,B
{
public void aaa()
{
//Any Code here
}
public static void main(String arg[])
{
//Statements
}
}
V
11. Variable names conflicts can be resolved by interface name e.g:
interface A
{
int x=10;
}
interface B
{
int x=100;
}
class Hello implement A,B
{
public static void Main(String arg[])
{
System.out.println(A.x);
System.out.println(B.x);
}
}
VI
}
}
VII
Encapsulation in Java
What is encapsulation?
VIII
Lets see an example to understand this concept better.
return ssn;
}
IX
}
}
Output:
Employee Name: Mario
Employee SSN: 112233
Employee Age: 32
Advantages of encapsulation:
1. It improves maintainability and flexibility and re-usability
2. The fields can be made read-only (If we don’t define setter
methods in the class) orwrite-only (If we don’t define the getter
methods in the class).
3. User would not be knowing what is going on behind the scene.