Showing posts with label abstract. Show all posts
Showing posts with label abstract. Show all posts

Wednesday 27 January 2016

Difference between abstract classes and interfaces

  1. Abstract classes doesn't support multiple inheritance but interface supports same.
  2. Abstract class can have final/non final and static/non static variables, but interfaces has only static and final variables.
  3. abstract keyword is used to create an abstract class and it can be used with methods also whereas interface keyword is used to create interface and it can’t be used with methods.
  4. Abstract classes can have methods with implementation whereas interface provides absolute abstraction and can’t have any method implementations.
  5. Abstract classes can have methods with implementation whereas interface provides absolute abstraction and can’t have any method implementations.
  6. Abstract classes can extend other class and implement interfaces but interface can only extend other interfaces.
  7. We can run an abstract class if it has main() method but we can’t run an interface because they can’t have main method implementation.

Example of abstract classes and interfaces in java

interface I{
void x();
void y();
void z();
}
abstract class SampleAbstract implements I{
public void z(){System.out.println("Inside z");}
}
class Sample extends SampleAbstract {
public void x(){System.out.println("Inside x");}
public void y(){System.out.println("Inside y");}
public void z(){System.out.println("Inside z");}
}
class TestOne{
public static void main(String args[]){
I a=new Sample ();
a.x();
a.y();
a.z();
}}  

Output:
Inside x
Inside y
Inside z



Friday 22 January 2016

Abstract classes


A class which is declared with abstract keyword is known as abstract class. Abstract means hidden and in java abstract classes have abstract and non abstract methods. Also java supports abstraction, it is a process of hiding the implementation details and showing only functionality to the user.

There are two ways of abstraction implementation in java and they are
  • abstract class
  • interface
Abstract Method:
A method that is declared as abstract and does not have implementation part is called abstract method

abstract void samplemethod(); // no method body

abstract class and abstract method

abstract class Car{
  abstract void run();
}
class Maruti extends Car{
void run(){System.out.println("running safely..");} 
public static void main(String args[]){
 Car obj = new Maruti();
 obj.run();
}


Output:
running safely..


Another example:

abstract class Cars{
abstract void drive();
}
class Honda extends Cars{
 void drive(){System.out.println("driving Honda");}
}
class Hyundai extends Cars{
 void drive(){System.out.println("driving Hyundai");}
}
  //method is called by programmer or user 
class AbstractionSample{
 public static void main(String args[]){
 Cars s=new Hyundai();
 s.drive();
}
}  


Output:
driving Hyundai