Abstract Class and Method in Polymorphism Java Prectice Card Tester


 Java Abstract Classes and Methods
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class). Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).

Abstract class in java can't be instantiated. An abstract class is mostly used to provide a base for subclasses to extend and implement the abstract methods and override or use the implemented methods in abstract class.

Example 

Card.java

public abstract class Card{
private String recipient;
public abstract void greeting();
}

Wedding.java

class Wedding extends Card{
public Wedding(){}
public Wedding ( String w){
recipient= w;}
public void greeting(){
System.out.println ("Dear" + recipient+",\n");
System.out.println ("Congratulation for  your wedding\n");}
}



KadRaya.java

class KadRaya extends Card{

public KadRaya(){}
public KadRaya( String r){
recipient = r;}

public void greeting(){
System.out.println("Dear"+ recipient+ ",\n");
System.out.println("Selamat Hari Raya!\n\n");
}
}

Birthday.java

class Birthday extends Card{
int age;

public Birthday(){}
public Birthday(String r,int years){
recipient= r;
age=years;
}

public void greeting(){
System.out.println ("Dear" + recipient+",\n");
System.out.println ("Happy" +age+"th Birthday\n");
}
}

CardTester.java

public class CardTester{

public static void main(String [] args){
Card kr = new KadRaya();
Card bd = new Birthday();
Card wd = new Wedding();
if (kr instanceof KadRaya){
kr.greeting();
}
else{
 System.out.println("error!");
}
if (bd instanceof Birthday){
bd.greeting();
}
else{
 System.out.println("error!");
}
if (wd instanceof Wedding){
wd.greeting();
}
else{
 System.out.println("error!");
}
}
}




Post a Comment

0 Comments