abstract constructor java code example
Example 1: how to use an abstract class in java
interface methods{
public void hey();
public void bye();
}
//unable to implement all the abstract methods in the interface so
// the other class automatically becomes abstract
abstract class other implements methods{
public void hey(){
System.out.println("Hey");
}
}
//able to implement all the methods so is not abstract
class scratch implements methods {
public void hey(){
System.out.println("Hey");
}
public void bye() {
System.out.println("Hey");
}
}
Example 2: abstract class java constructor
/**
* Simple Java program to prove that abstract class can have constructor in Java.
* @author http://java67.blogspot.com
*/
public class AbstractConstructorTest {
public static void main(String args[]) {
Server server = new Tomcat("Apache Tomcat");
server.start();
}
}
abstract class Server{
protected final String name;
public Server(String name){
this.name = name;
}
public abstract boolean start();
}
class Tomcat extends Server{
public Tomcat(String name){
super(name);
}
@Override
public boolean start() {
System.out.println( this.name + " started successfully");
return true;
}
}
Output:
Apache Tomcat started successfully
Example 3: Can you add a constructor to an abstract class
We can create constructor in abstract class , it does’nt give any compilation
error.