Adding extra exercises for Polymorphism and Inheritance

This commit is contained in:
Marcus Vinicius de Carvalho 2024-10-23 18:53:40 +08:00
parent 0b1fb6c74a
commit bd3c2688f4
5 changed files with 63 additions and 0 deletions

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -0,0 +1,9 @@
public class ClassA {
public void method1() {
System.out.println("ClassA.method1");
}
public void method2() {
System.out.println("ClassA.method2");
}
}

View File

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

View File

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

25
T5Q2-Marcus/src/Main.java Normal file
View File

@ -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
}
}