Professional Documents
Culture Documents
Let’s get back to the point, when I say argument list it means the parameters that
a method has: For example the argument list of a method add(int a, int b) having
two parameters is different from the argument list of the method add(int a, int b, int
c) having three parameters.
Three ways to overload a method
In order to overload a method, the argument lists of the methods must differ in
either of these:
1. Number of parameters.
For example: This is a valid case of overloading
add(int, int)
add(int, int, int)
2. Data type of parameters.
For example:
add(int, int)
add(int, float)
3. Sequence of Data type of parameters.
For example:
add(int, float)
add(float, int)
The purpose of Method Overriding is clear here. Child class wants to give its own
implementation so that when it calls this method, it prints Boy is eating instead of
Human is eating.
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}
Output:
Boy is eating
Advantage of method overriding
The main advantage of method overriding is that the class can give its own
specific implementation to an inherited method without even modifying the
parent class code.
This is helpful when a class has several child classes, so if a child class needs to
use the parent class method, it can use it and the other classes that want to have
different implementation can use overriding feature to make changes without
touching the parent class code
A. Introducing Class Concept in Java Programming
A class, in the context of Java, are templates that are used to create objects, and to
define object data types and methods. Core properties include the data types and
methods that may be used by the object. All class objects should have the basic class
properties.
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
C. Explanation of Syntax:
Class name
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
2. When a number of objects are created for the same class, the same copy
Class Methods
11. These methods are meant for operating on class data i.e Class Instance Variables.
12. Methods have return type as well as parameter list. We are going to learn this
// two fields
public int breadth;
public int length;
// two methods
public void setLength(int newValue) {
length = newValue;
}