more lessons
This commit is contained in:
11
java/inheritance/Animal.java
Normal file
11
java/inheritance/Animal.java
Normal file
@ -0,0 +1,11 @@
|
||||
public class Animal {
|
||||
public String name;
|
||||
|
||||
public Animal(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void make_sound() {
|
||||
System.out.println(this.name + ":");
|
||||
}
|
||||
}
|
17
java/inheritance/Cat.java
Normal file
17
java/inheritance/Cat.java
Normal file
@ -0,0 +1,17 @@
|
||||
// make the class cat inherit from Animal
|
||||
public class Cat extends Animal {
|
||||
// java requires an explicit constructor when the supertype awaits parameters in the constructor
|
||||
public Cat(String name) {
|
||||
// call supertype constructor
|
||||
super(name);
|
||||
}
|
||||
|
||||
// override make_sound
|
||||
public void make_sound() {
|
||||
// optional: call the parent class function
|
||||
super.make_sound();
|
||||
|
||||
// add additional functionality
|
||||
System.out.println("meow");
|
||||
}
|
||||
}
|
14
java/inheritance/Dog.java
Normal file
14
java/inheritance/Dog.java
Normal file
@ -0,0 +1,14 @@
|
||||
public class Dog extends Animal {
|
||||
// java requires an explicit constructor when the supertype awaits parameters in the constructor
|
||||
public Dog(String name) {
|
||||
// call supertype constructor
|
||||
super(name);
|
||||
}
|
||||
|
||||
// override the method make_sound
|
||||
public void make_sound() {
|
||||
// implement own functionality
|
||||
System.out.println("doggo " + this.name + " says:");
|
||||
System.out.println("woof!");
|
||||
}
|
||||
}
|
9
java/inheritance/Program.java
Normal file
9
java/inheritance/Program.java
Normal file
@ -0,0 +1,9 @@
|
||||
public class Program {
|
||||
public static void main(String[] args) {
|
||||
Dog d = new Dog("buster");
|
||||
Cat c = new Cat("mittens");
|
||||
|
||||
d.make_sound();
|
||||
c.make_sound();
|
||||
}
|
||||
}
|
8
java/inheritance/README.md
Normal file
8
java/inheritance/README.md
Normal file
@ -0,0 +1,8 @@
|
||||
# Inheritance
|
||||
|
||||
Relevant files:
|
||||
|
||||
- [Program.java](./Program.java)
|
||||
- [Animal.java](./Animal.java)
|
||||
- [Cat.java](./Cat.java)
|
||||
- [Dog.java](./Dog.java)
|
Reference in New Issue
Block a user