-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInheritance.java
More file actions
87 lines (61 loc) · 1.82 KB
/
Copy pathInheritance.java
File metadata and controls
87 lines (61 loc) · 1.82 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
83
84
85
86
87
package oop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* Inheritance: code reuse between classes (extends, super).
*/
// Base class (superclass)
class Animal {
private static final Logger logger = LoggerFactory.getLogger(Animal.class);
protected final String name;
Animal(String name) {
this.name = name;
}
void eat() {
logger.info("{} is eating.", name);
}
void makeSound() {
logger.info("{} makes a generic sound.", name);
}
}
// Derived class (subclass) that inherits from Animal
class Dog extends Animal {
private static final Logger logger = LoggerFactory.getLogger(Dog.class);
Dog(String name) {
super(name);
}
@Override
void makeSound() {
logger.info("{} says: Woof!", name);
}
void fetchBall() {
logger.info("{} goes to fetch the ball.", name);
}
}
// Derived class (subclass) that inherits from Animal
class Cat extends Animal {
private static final Logger logger = LoggerFactory.getLogger(Cat.class);
Cat(String name) {
super(name);
}
@Override
void makeSound() {
logger.info("{} says: Meow!", name);
}
}
public class Inheritance {
private static final Logger logger = LoggerFactory.getLogger(Inheritance.class);
// Private constructor to prevent instantiation from outside the class
private Inheritance() {
throw new IllegalStateException("Utility class");
}
public static void main() {
Dog dog = new Dog("nameDog");
Cat cat = new Cat("nameCat");
dog.eat(); // Method inherited from Animal
dog.makeSound(); // Overridden method
dog.fetchBall(); // Dog's own method
cat.eat(); // Method inherited from Animal
cat.makeSound(); // Overridden method
}
}