Last active
August 29, 2015 14:04
-
-
Save kenorb/f633a7b83ce119b78e0d to your computer and use it in GitHub Desktop.
Abstract Class Demo in Java.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Abstract Class Demo. | |
* | |
* - A class which has at least one abstract method is called as abstract class. | |
* - Abstract class is a class which has no complete implementation. | |
* - Abstract class cannot be instantiated. | |
* - An abstract class can have abstract and concrete methods. | |
* | |
* Abstract method is a method which has no body or implementation. | |
* Concrete method is a method which has the body (e.g. closing curly brackets). | |
* | |
* Note: | |
* If a class extends abstract class, | |
* it must provide an implementation for all abstract methods of its superclass, | |
* otherwise class it-self becomes subclass. | |
* | |
* How to run: | |
* javac AbstractClass.java | |
* java AbstractDemo | |
*/ | |
abstract class A { | |
abstract void getA(); // Abstract method which has no body. | |
void display() { // Concrete method which has the body. | |
System.out.println("From display()"); | |
} | |
} | |
class B extends A { // Here the class B is a concrete class. | |
void getA() { // A method with an implementation. | |
System.out.println("From getA()"); | |
} | |
// display() is inherited from class A. | |
} | |
class AbstractDemo { | |
public static void main(String[] args) { | |
B b1 = new B(); | |
b1.getA(); | |
b1.display(); | |
// A a1 = new A(); // error: A is abstract; cannot be instantiated | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment