forked from coder2hacker/Explore-open-source
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractClassExample.java
More file actions
82 lines (78 loc) · 2.08 KB
/
AbstractClassExample.java
File metadata and controls
82 lines (78 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
abstract class Shape{
//abstract method
abstract void draw();
abstract void area();
//non-abstract method
void same() {
System.out.println("Same for all");
}
/*
* To write a method without body,
* add 'abstract' before method name.
*
* An abstract class may contain more than one abstract methods and
* non-abstract methods also.
*
* For Non-Abstract method,
* the method will be inherited but no need to write further definition.
*
* For Abstract method,
* We have to write further definition.
*/
}
abstract class Ellipse extends Shape{
}
/*
* If a child does not implement all the abstract methods of abstract parent class,
* then the child class must need to be declared abstract as well.
*/
class Rectangle extends Shape{
void draw() {
System.out.println("Rectangle Drawing");
}
void area() {
System.out.println("Rectangle Area");
}
}
/*
* When Rectangle class inherits an abstract class "Shape",
* then Rectangle class must contain those abstract methods with body.
*
* Without implementation of abstract method will generate error.
*/
class Circle extends Shape{
void draw() {
System.out.println("Circle Drawing");
}
void area() {
System.out.println("Circle Area");
}
}
public class AbstractClassExample {
public static void main(String[] args) {
//Shape s = new Shape();
/*
* We cannot instantiate the abstract class that means
* we can't create any object of an abstract class
*/
Shape rec = new Rectangle();
Shape cir = new Circle();
/*
* Rectangle is a sub-Category of Shape.
* Circle is a sub-Category of Shape.
*/
rec.draw();
rec.area();
rec.same();
cir.draw();
cir.area();
cir.same();
}
}
/*
* Why we can't create object of abstract class?
* Abstract contains abstract or non abstract methods. And we know
* abstract method does not have any definition in abstract class.
* So, creating an object of abstract class and calling abstract method
* by that object has no implementation. So, JAVA does not allow.
*/