+ 17
What is purpose of abstract class in java ?
4 Antworten
+ 9
Abstract methods are similar to 'prototype' or 'blueprint' of real methods
+ 4
Abstract class gives you the ability to define methods without body, however, you'll have to override these methods when inheriting from abstract classes.
example -
suppose you define an abstract game class which has all the game logic in it.
You define one function which fires when the user clicks the left mouse button and leave the body blank.
This allows you to define a level1 class inheriting from Game class in which the mouse click fires a bullet.
And a level2 class in which the mouse click swings a sword.
You inherit the abstract Game class and it forces you to override the mouse click function which you can implement however you want and the functionally which calls that function remains in the Game class.
0
Not working
- 1
class Main {
public static void main(String[] args) {
//do not touch this code
Monopoly monopoly = new Monopoly();
Chess chess = new Chess();
Battleships battleships = new Battleships();
monopoly.play();
chess.play();
battleships.play();
}
}
abstract class Game {
abstract String getName();
abstract void play();
}
class Monopoly extends Game {
//give "Monopoly" name to game
String getName() {
return monopoly;
}
// play method should print "Buy all property."
void play() {
System.out.println("Buy all property");
}
}
class Chess extends Game {
//give "Chess" name to game
String getName() {
return chess;
}
// play method should print "Kill the enemy king"
void play() {
System.out.println("Kill the enemy king");
}
}
class Battleships extends Game {
//give "Battleships" name to game
String getName() {
return battleships;
}
// play method should print "Sink all ships"
void play() {
System.out.println("Sink all ships");
}
}