A Java Override Overload
Java works from the bottom up as an object-oriented language. This means it supports classes, objects and inheritance as part of its functionality. These concepts, as integral parts of object-oriented programming, imply that Java would support method overriding and method overloading. These two programmatical concepts help Java programmers extend base classes and to create flexible classes in their code.
-
Java Classes
-
Classes are the blueprints for "objects" in the Java languages. Programmers write class to define data types that represent certain aspects of a program, such as network connections or drawings. The class and the object are fundamental parts of the Java programming language, in that beside basic data types such as integers or bytes, everything in Java is represented as an object. Java programs are often based on the interactions between objects.
Methods and Inheritance
-
When a programmer defines a class, she defines "methods" as part of that class. Methods represent operations that an object declared from a class can use. For example, an object declared from class "Ball" that contains a method "calculateArea" could execute the method and calculate its own surface area. Furthermore, programmers can create classes that "inherit" functionality from other, base classes. So a class "SoccerBall" could inherit functionality from class ball, and use the "calculateArea" method as if it were an object of class "Ball."
-
Overloading Methods
-
Often, when a programmer creates a class, she might want to have methods that share the same name, but take different values as arguments. For example, the "calculateArea" method might take zero arguments. However, if the programmer wants another version of the "calculateArea" method that saves the result to a file, then she could simply declare another method with the same name that takes a File object as an argument. This way, the compiler will know which method to call based on the argument supplied:
public int calculateArea(){
//calculates the area and returns an integer
}public void calculateArea(File o){
//calculates area and prints it to a file
}
Overriding Methods
-
If a class derives functionality from another class, as in the case of "Ball" and "SoccerBall," the class that inherits from the base class can "override" the methods of the base class. Programmers often do this if the inheriting class has a similar functionality, but specialized for the class. To illustrate this, the class "Ball" might have a "calculateArea" method. The class "SoccerBall" that inherits from "Ball" can use the original method, or it can override the method by declaring its own version of the method in its class definition:
class Ball{
public int calculateArea(){
//Ball's method
}
}class SoccerBall extends Ball{
public int calculateArea(){
//SoccerBall's version, will not call Ball's version
}
}
-