Java Inheritance and Polymorphism

Do inheritance and polymorphism make up the IS-A relationship? And is it true that inheritance and “overriding” polymorphism occur at run time, while “overloading” polymorphism occurs at compile time? The reason I'm asking about this is because many forums seem to give conflicting and often confusing answers.

Thank!

+5
source share
6 answers

For your first part of the question, I think Wikipedia provides a good definition:

- - , , - . , ( ()) , , . , , .

Wikipedia, - , , . " , " .

Java , , . Java . , , . , Serializable Cloneable, . , , Java . .

, .

, , . , , , .

, , , , . , , .

Java (JLS) 15.12 , , .

, . JLS 15.12.2:

, , .

, .

, , .

public class ChooseMethod {
   public void doSomething(Number n){
    System.out.println("Number");
   }
}

, .

public class MethodChooser {
   public static void main(String[] args) {
    ChooseMethod m = new ChooseMethod();
    m.doSomething(10);
   }
}

main, Number.

ChooseMethod ( ).

public void doSomething(Integer i) {
 System.out.println("Integer");
}

main, Number.

, . MethodChooser ( ) , Integer.

, , , .

, , .

, , .

public class ChooseMethodA {
   public void doSomething(Number n){
    System.out.println("Number A");
   }
}

:

public class ChooseMethodB extends ChooseMethodA {  }

MethodChooser :

public class MethodChooser {
    public static void main(String[] args) {
        ChooseMethodA m = new ChooseMethodB();
        m.doSomething(10);
    }
}

, Number A, , ChooseMethodB, ChooseMethodA.

MethodChooserB:

public void doSomething(Number n){
    System.out.println("Number B");
}

, .

Number B

, , MethodChooser.

+8

: -.

- , . . Duck Typing

- " ", . .

+5

, .

, , , , .

+1

- . , .

; " ".

, :

class A extends B
{
}
0

IS-A. .

"" - .

0

• , .

• , . , . , , .

• Java , , . , Runnable, Comparator Serializable , . , . , Serializable, Collections.sort(), Comparator.

• Both polymorphisms and inheritance allow object-oriented programs to evolve. For example, using Inheritance, you can define new types of users in the authentication system, and using Polymorphism, you can use the authentication code already written. Since Inheritance guarantees minimal behavior of the base class, a method that depends on the superclass or superinterface can still accept the object of the base class and can authenticate it.

0
source

All Articles