-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInheritance.java
More file actions
52 lines (44 loc) · 1.34 KB
/
Inheritance.java
File metadata and controls
52 lines (44 loc) · 1.34 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
// Inheritance.java
// This class demonstrates the concept of inheritance in Java.
// Inheritance allows one class to inherit the properties and methods of another class.
class Animal {
// Properties of the Animal class
String name;
int age;
// Constructor for the Animal class
Animal(String name, int age) {
this.name = name;
this.age = age;
}
// Method to display animal details
void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
// Dog class inherits from Animal class
class Dog extends Animal {
// Additional property for Dog class
String breed;
// Constructor for Dog class
Dog(String name, int age, String breed) {
// Call the constructor of the superclass (Animal)
super(name, age);
this.breed = breed;
}
// Method to display dog details
void displayDogInfo() {
// Call the displayInfo method from the Animal class
displayInfo();
System.out.println("Breed: " + breed);
}
}
// Main class to test inheritance
public class Inheritance {
public static void main(String[] args) {
// Create an instance of Dog
Dog myDog = new Dog("Buddy", 3, "Golden Retriever");
// Display the details of the dog
myDog.displayDogInfo();
}
}