Abstraction in java means focus on main thing instead of focusing on its implementation. It can be achieved through abstract class and interface.
The whole idea of abstract classes is that they can contain some behaviour or data which you require all subclasses to contain.
The whole idea of abstract classes is that they can contain some behaviour or data which you require all subclasses to contain.
- abstract methods ends with semi column
- abstract public void method();
- no implementation is required for abstract method
- Abstract classes can have Constructors, Member variables and Normal methods.
- An abstract class may or may not have an abstract method. But if any class has even a single abstract method, then it must be declared abstract.
- If a class extending an abstract class it must implements the abstract method.
- You can't create object of an abstract class
Below code will explain the use
without abstract
class Samsung
{
public void showConfig(Samsung obj){
System.out.println("Samsumg");
}
}
class Iphone
{
public void showConfig(Iphone obj){
System.out.println("iPhone");
}
}
class AbsDemo
{
public static void main (String args[])
{
Samsung sam = new Samsung();
Iphone ip = new Iphone();
AbsDemo a = new AbsDemo();
a.showConfig(sam);
a.showConfig(ip);
}
public void showConfig(Iphone o){
o.showConfig(o);
}
public void showConfig(Samsung o){
o.showConfig(o);
}
}
With abstract
abstract class Phone
{
public abstract void showConfig(Phone o);
}
class Samsung extends Phone
{
public void showConfig(Phone obj){
System.out.println("Samsumg");
}
}
class Iphone extends Phone
{
public void showConfig(Phone obj){
System.out.println("iPhone");
}
}
class AbsDemo2
{
public static void main (String args[])
{
Samsung sam = new Samsung();
Iphone ip = new Iphone();
showConfig(sam);
showConfig(ip);
}
public static void showConfig(Phone o){
o.showConfig(o);
}
}
No comments:
Post a Comment