Ad Code

Responsive Advertisement

Overriding in the Java programming language

Overriding in the Java programming language, java like other programming languages, supports the concept of (Overriding), which means defining the function that the derived class inherited from the main Superclass, so that this new function is similar to the inherited function in terms of form only, i.e. It has the same name, type, and the number of parameters, but in fact, its content is different, and the main objective of this concept is to allow the derived class to know the functions according to his needs.


overriding in the Java programming language


Conditions for implementing functions overriding in the Java programming language


  • The modifiers used with the new function must be the same as the old function, and its type must be public or protected.
  • The number and type of parameters of the new function must be identical to the number and type of parameters of the old function.
  • The return type of the new function must be the same as the return type of the old function.
  • A function defined by type (private) cannot be applied to the concept of (override), because type (private) prevents direct access to the function from the derived subclass.
  • A function defined by type (final) cannot be applied to the concept of (override), because the type (final) prevents changing the function's content after it has been defined.
  • The function defined by type (static) cannot be applied to the concept of (override), but it can be defined again anywhere because the type (static) makes the function common to all classes.
  • We cannot apply the concept of (override) to constructors.



Overriding in java example


The following is an example of using the concept of (overriding) in the Java programming language:


public class Country { 

public void language() {

}

public class Australia extends Country {

}

public class jordan extends Country {

public void language () {

 system. out.println( "English");

 }

 }

 

Here a class named (Country) has been defined, which contains a function called (()language), and other classes have also been defined, as they inherit from the (Country) class, so all of them will contain the function (()language), here is the idea that any A class that inherits from (Country) class will have to define the (()language) function again to fit it.