more lessons

This commit is contained in:
2020-05-24 17:04:37 +02:00
parent 5abcc6ed5a
commit 804adb3b89
25 changed files with 348 additions and 1 deletions

View 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
View 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
View 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!");
}
}

View 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();
}
}

View File

@ -0,0 +1,8 @@
# Inheritance
Relevant files:
- [Program.java](./Program.java)
- [Animal.java](./Animal.java)
- [Cat.java](./Cat.java)
- [Dog.java](./Dog.java)