From bd3c2688f429110115af79653a6157f6a92f6765 Mon Sep 17 00:00:00 2001 From: ivs Date: Wed, 23 Oct 2024 18:53:40 +0800 Subject: [PATCH] Adding extra exercises for Polymorphism and Inheritance --- T5Q2-Marcus/T5Q2-Marcus.iml | 11 +++++++++++ T5Q2-Marcus/src/ClassA.java | 9 +++++++++ T5Q2-Marcus/src/ClassB.java | 9 +++++++++ T5Q2-Marcus/src/ClassC.java | 9 +++++++++ T5Q2-Marcus/src/Main.java | 25 +++++++++++++++++++++++++ 5 files changed, 63 insertions(+) create mode 100644 T5Q2-Marcus/T5Q2-Marcus.iml create mode 100644 T5Q2-Marcus/src/ClassA.java create mode 100644 T5Q2-Marcus/src/ClassB.java create mode 100644 T5Q2-Marcus/src/ClassC.java create mode 100644 T5Q2-Marcus/src/Main.java diff --git a/T5Q2-Marcus/T5Q2-Marcus.iml b/T5Q2-Marcus/T5Q2-Marcus.iml new file mode 100644 index 0000000..c90834f --- /dev/null +++ b/T5Q2-Marcus/T5Q2-Marcus.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/T5Q2-Marcus/src/ClassA.java b/T5Q2-Marcus/src/ClassA.java new file mode 100644 index 0000000..754836c --- /dev/null +++ b/T5Q2-Marcus/src/ClassA.java @@ -0,0 +1,9 @@ +public class ClassA { + public void method1() { + System.out.println("ClassA.method1"); + } + + public void method2() { + System.out.println("ClassA.method2"); + } +} diff --git a/T5Q2-Marcus/src/ClassB.java b/T5Q2-Marcus/src/ClassB.java new file mode 100644 index 0000000..5515d18 --- /dev/null +++ b/T5Q2-Marcus/src/ClassB.java @@ -0,0 +1,9 @@ +public class ClassB extends ClassA { + public void method2() { + System.out.println("ClassB.method2"); + } + + public void method3() { + System.out.println("ClassB.method3"); + } +} diff --git a/T5Q2-Marcus/src/ClassC.java b/T5Q2-Marcus/src/ClassC.java new file mode 100644 index 0000000..9f4f167 --- /dev/null +++ b/T5Q2-Marcus/src/ClassC.java @@ -0,0 +1,9 @@ +public class ClassC extends ClassB { + public void method3() { + System.out.println("ClassC.method3"); + } + + public void method4() { + System.out.println("ClassC.method4"); + } +} diff --git a/T5Q2-Marcus/src/Main.java b/T5Q2-Marcus/src/Main.java new file mode 100644 index 0000000..f764a31 --- /dev/null +++ b/T5Q2-Marcus/src/Main.java @@ -0,0 +1,25 @@ +public class Main { + public static void main(String[] args) { + // I +// ClassA a = new ClassB(); +// ClassB b = (ClassB) a; +// b.method2(); // ClassB.method2 +// b.method1(); // ClassA.method1 + + // II +// ClassA c = new ClassB(); +// ClassC d = (ClassC) c; // Runtime error here +// d.method3(); // Never executed + + // III +// ClassA e = new ClassC(); +// ClassB f = (ClassB) e; +// f.method3(); // ClassC.method3 +// f.method2(); // ClassB.method2 +// f.method1(); // ClassA.method1 + + // IV +// ClassC g = (ClassC) new ClassA(); // Runtime error +// g.method1(); // never executed + } +} \ No newline at end of file