abstratcion i java code example
Example 1: abstraction in java
Sometimes we may come across a situation
where we cannot provide implementation to
all the methods in a class. We want to leave the
implementation to a class that extends it.
In that case we declare a class
as abstract by using abstract keyword on method
signature.In my framework I have created my
PageBase class as super
class of the all page classes.
I have collected all common elements
and functions into PageBase class and
all other page classes extent PageBase class.
By doing so, I don't have to locate very
common WebElements and it provides
reusability in my framework.
Also
1)Abstract classes cannot be instantiated
2)An abstarct classes contains abstract method,
concrete methods or both.
3)Any class which extends abstarct class must
override all methods of abstract class
4)An abstarct class can contain either
0 or more abstract method.
Example 2: abstract class java
// abstract class
abstract class Shape
{
// abstract method
abstract void sides();
}
class Triangle extends Shape
{
void sides()
{
System.out.println("Triangle shape has three sides.");
}
}
class Pentagon extends Shape
{
void sides()
{
System.out.println("Pentagon shape has five sides.");
}
public static void main(String[] args)
{
Triangle obj1 = new Triangle();
obj1.sides();
Pentagon obj2 = new Pentagon();
obj2.sides();
}
}
Example 3: abstract class example in java
//abstract parent class
abstract class Animal{
//abstract method
public abstract void sound();
}
//Dog class extends Animal class
public class Dog extends Animal{
public void sound(){
System.out.println("Woof");
}
public static void main(String args[]){
Animal obj = new Dog();
obj.sound();
}
}