Note that there are some explanatory texts on larger screens.

plurals
  1. POJava inheritance (method overriding and overloading)
    primarykey
    data
    text
    <p>Besides that Java inheritance is a fundamental feature of the language, I have some questions.<br> Here is the source for my testing example:</p> <pre><code>class MyClass{ public void say(String t){ System.out.println("Hello MyClass "+t); } public void print(MyClass t){ System.out.println("MyClass is printed"); } public void anotherPrint(int i){ System.out.println("MyClass is printed again"); } } class MyClass2 extends MyClass{ public void say(String t){ System.out.println("Hello MyClass2 "+t); } public void print(MyClass2 t){ System.out.println("MyClass2 is printed"); } public void anotherPrint(double i){ System.out.println("MyClass2 is printed again"); } } public class HelloWorld{ public static void main(String []args){ MyClass klass = new MyClass2(); klass.say("h"); //Question 1 (Prints: "Hello MyClass2 h") klass.print(new MyClass2()); //Question 2 (Prints: "MyClass is printed") klass.print(new MyClass()); //Question 3 (Prints: "MyClass is printed") klass.anotherPrint(1); //Question 4 (Prints: "MyClass is printed again") klass.anotherPrint(1.0); //Question 5 (Throws Exception!) } } </code></pre> <p><b>I have the following questions:</b><br><br> 1. The klass object is instance of MyClass. Why does it execute the method from the MyClass2 class?<br><br> 2,3 . At question 1 klass calls the method of the Class2 class. Here I used a parameter that fits to each one of the overridden and overloaded (simultaneously) methods. Why klass object always calls the method from the MyClass class?<br><br> 4. It is normal. No question at all.<br><br> 5. It is right to throw an exception. The klass object does not have this method with double parameter. But, why it is not called the method from the MyClass2 class, just like it happened at Question 1?<br><br></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload