Qual è la differenza tra l'overload di un metodo e l'override in Java?

10

Qual è la differenza tra sovraccaricare un metodo e sovrascriverlo in Java?

C'è una differenza nella firma del metodo, nell'indicatore di accesso, nel tipo di reso, ecc.?

    
posta user63948 10.09.2012 - 15:28
fonte

4 risposte

41

Per sovraccaricare un metodo con un nuovo metodo, il nuovo metodo dovrebbe avere una firma diversa. Cioè due metodi sovraccaricati hanno lo stesso nome, ma diversi parametri. Ecco un esempio di due metodi in overload:

boolean isOdd(int number) { ... };
boolean isOdd(float number) { ... };

In base ai tipi di parametro, verrà chiamato il metodo corrispondente. Tieni presente che la modifica del tipo di reso non è sufficiente (anche se puoi farlo in aggiunta).

Quando un metodo viene sovrascritto, il nuovo metodo ha la stessa firma e in alcuni casi sostituisce il metodo sottoposto a override. Ecco un esempio di un metodo sottoposto a override:

public class A 
{
     public void someMethod() { ... }
}

public class B extends A
{
     public void someMethod() { ... }
}

La scelta viene effettuata in base al tipo di oggetto. Ad esempio,

A someA = new B();
someA.someMethod();

chiamerà il someMethod di B . Puoi (e dovresti) aggiungere l'annotazione @ Override:

public class B extends A
{
     @Override
     public void someMethod() { ... }
}

Ora, se cambi casualmente i parametri in B, il compilatore ti informerà che non stai sovrascrivendo someMethod () ma lo stai sovraccaricando.

    
risposta data 10.09.2012 - 15:31
fonte
13

Sovraccarico, i metodi hanno lo stesso nome ma diversi parametri.

Override, l'implementazione data nella classe base viene sostituita con quella nella sottoclasse.

    
risposta data 10.09.2012 - 17:54
fonte
7

I concetti che chiedi sono trattati nei tutorial di Java.

La spiegazione per l'override è data come segue:

An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.

The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type.

When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, it will generate an error. For more information on @Override, see Annotations...

Il sovraccarico è spiegato nel tutorial come segue:

The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled "Interfaces and Inheritance".

Suppose that you have a class that can use calligraphy to draw various types of data (strings, integers, and so on) and that contains a method for drawing each data type. It is cumbersome to use a new name for each method—for example, drawString, drawInteger, drawFloat, and so on. In the Java programming language, you can use the same name for all the drawing methods but pass a different argument list to each method. Thus, the data drawing class might declare four methods named draw, each of which has a different parameter list...

Overloaded methods are differentiated by the number and the type of the arguments passed into the method...

You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.

The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.


Note: Overloaded methods should be used sparingly, as they can make code much less readable.


Sopra la spiegazione per il sovraccarico menziona le qualifiche discusse nella lezione intitolata " Interfacce ed eredità ":

In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass methods—they are new methods, unique to the subclass.

    
risposta data 10.09.2012 - 17:33
fonte
2

Il sovraccarico di un metodo viene in genere definito come "fornitura di più metodi disponibili con lo stesso nome, che differiscono dal numero e dal tipo di input e output". In genere, il concetto è che si desideri essere in grado di eseguire la stessa operazione di base in base a diversi insiemi di input: è possibile, ad esempio, "aggiungere" due valori di tipo numerico, tuttavia è solitamente importante sapere quale sia il tipo esatto di il valore è tale da poter sfruttare o pianificare comportamenti specifici di quel tipo. Come tale, definiresti un metodo per ciascuna combinazione di tipi numerici (e / o collezioni) che desideri supportare. Tutti questi metodi hanno lo stesso nome, ma "firme" differenti; in fase di compilazione, il compilatore abbinerà una chiamata a un particolare nome di metodo con una data combinazione di input a un puntatore specifico nella memoria dell'applicazione utilizzata per memorizzare il codice.

L'override di un metodo viene in genere definito come "fornitura di un'implementazione diversa in una classe derivata di un metodo con una particolare firma definita nella classe base". Ci sono molti motivi per scavalcare un metodo; praticamente tutti hanno in comune il fatto che la classe derivata ha una conoscenza aggiuntiva di ciò che deve essere fatto, che non può essere conosciuto dalla classe base. Ci sono due modi di sovrascrivere nella maggior parte dei linguaggi OO; l'override può sostituire il metodo della classe base, oppure può estendere il metodo della classe base. La differenza è solitamente che una classe derivata che sta estendendo un'implementazione di una classe base chiamerà la versione sovrascritta della classe base del metodo ad un certo punto durante l'esecuzione del metodo di override. Ciò consente alle classi di override di "riutilizzare" le aree comuni dell'operazione che sono contenute nella classe base.

    
risposta data 10.09.2012 - 18:24
fonte

Leggi altre domande sui tag