10.1 | Class
A class is a template from which objects are created. A class declaration typically contains a set of attributes (instance variables) and functions (methods).
10.2 | Methods
In Java, functions, and procedures are called methods. Methods can include zero or more input parameters and zero or one return parameter. The following code shows some method declarations. An arithmetic class has two methods printSum and getSum. method printSum has two input parameters both of integer type and no return parameter. while method getSum has two integer type input parameter and one integer type return parameter.
10.2.1 | Method Overloading
In Java, method overloading occurs when two or more methods in the same class have the same name but different parameters. Two methods can be considered overloaded if any of the below conditions are true:
- The number of parameters is different for the methods.
- The parameter types (input or return) are different.
Class ArithmeticClass below has two methods with same name getSum. these two methods are overloaded as the number of input parameters is different of both.
10.2.2 | Method Overriding
Overriding a method involves defining a method in a subclass that has the same signature (input and return parameter) as a method in a superclass. Then, when that method is called, the method in the subclass is found and executed instead of the one in the superclass. The following code overriding method print. The code below shows the classes SuperClass and SubClass. SubClass overrides the print method of its superclass. MainClass shows different ways of calling the overridden method of a subclass as well as the original method of the superclass.
10.2.3 | Variable and Method Scope
Java has reserved keywords to define the scope of variables methods and classes.
private keyword is used to declare variables and methods that are to be accessible only within the class.
protected keyword is used to declare variables and methods that are to be accessible only within the class or any class that extends to this class.
public keyword is used to declare variables and methods that are to be accessible within the class and as well as outside of class.