Abstraction is one of the four major concepts behind object-oriented programming (OOP). OOP questions are very common on job interviews, so you may expect questions about abstraction on your next Java job interview.
Introduction
Notes:
- Interfaces have only abstract methods which have to implements by a class that is compulsory.
- Abstract class have both abstract method and non-abstract method that abstract methods have to implements a class.
- We can't create object both abstract classes and interfaces. only create a object for a Class.
- Interface rather than abstract class has a advantage which has abstract method and non-abstract methods that can only implements the abstract method but you don't want to implements the non-abstract method, because non-abstract methods already have declared.
Interface Example :
interface ICalc{
public int add(int x,int y);
public int sub(int x,int y);
}
class Calculator implements ICalc{
public int add(int x,int y){
return x+y;
}
public int sub(int x,int y){
return x-y;
}
}
public class Samle {
public static void main(String[] args){
Calculator calc = new Calculator();
System.out.println("Addition: "+calc.add(10,20));
System.out.println("Subtraction: "+calc.sub(50,40));
System.out.println();
}
}
Abstract Class Example:
abstract class SciClac{
abstract public int add(int x, int y);
abstract public int sub(int x,int y);
public int multi(int x, int y){
return x*y;
}
}
class SciCalculator extends SciClac{
public int add(int x, int y){
return x+y;
}
public int sub(int x,int y){
return x-y;
}
}
public class Samle {
public static void main(String[] args){
SciCalculator sc = new SciCalculator();
System.out.println("Addition: "+sc.add(10,20));
System.out.println("Subtraction: "+sc.sub(50,40));
System.out.println("Multiply: "+sc.multi(50,40));
}
}
No comments:
Post a Comment