Class Inheritance

Topic Progress

Inheritance

Create a new project called Inhitance and create the classes by copying and pasting the code below

1
2
3
4
5
6
7
8
9
10
11
12
13
class Calculation {
   int z;
   
   public void addition(int x, int y) {
      z = x + y;
      System.out.println("The sum of the given numbers:"+z);
   }
   
   public void Subtraction(int x, int y) {
      z = x - y;
      System.out.println("The difference between the given numbers:"+z);
   }
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class MyCalculation extends Calculation {
    public void multiplication(int x, int y) {
        z = x * y;
        System.out.println("The product of the given numbers:" + z);
    }

    public static void main(String args[]) {
        int a = 20, b = 10;
        MyCalculation demo = new MyCalculation();
        demo.addition(a, b);
        demo.Subtraction(a, b);
        demo.multiplication(a, b);
    }

}

Extension

In the calculation class create a multiply method and change the MyCalculation class to add the third number

Example 2 Animals

Create a project called Animal and a class called Animal

Run and test

Uncomment the lines, run, test and explain what is happening

Experiment by adding more animals and more methods in the Animal class that are called in the subclasses

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
class Animal {
    void eat() {
        System.out.println("eating...");
    }

    void breath() {
        System.out.println("breathing...");
    }
}

class Dog extends Animal {
    // {

    // super.breath();
    // }
    void bark() {
        System.out.println("barking...");
    }
}

class BabyDog extends Dog {
    void weep() {
        System.out.println("weeping...");
    }
}

class TestInheritance2 {
    public static void main(String args[]) {
        BabyDog d = new BabyDog();
        d.weep();
        d.bark();
        d.eat();
        // d.breath();
    }
}

Inheritance

Extension

Read about inheritance and do the following tutorial

Inheritance Tutorial 1
Inheritance Tutorial 2

FInd more tutorials to test in Eclipse