Experiment 7
Experiment 7
: 07
Title: Program to define class, methods and objects. Demonstrate method overloading.
Theory:
An entity that has state and behavior is known as an object e.g., chair, bike, marker,
pen, table, car, etc. It can be physical or logical (tangible and intangible). The example of an
intangible object is the banking system.
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
A variable which is created inside the class but outside the method is known as an
instance variable. Instance variable doesn't get memory at compile time. It gets memory at
runtime when an object or instance is created. That is why it is known as an instance variable.
The new keyword is used to allocate memory at runtime. All objects get memory in
Heap memory area.
Object and Class Example: main within the class
class Student{
//defining fields
int id; //field or data member or instance variable
String name;
0
null
Output
class Student{
int id;
0 String name;
null
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Output
class Student{
int rollno;
String name;
void displayInformation(){
System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
111 Karan
222 Aryan
Output
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading. If we have to perform only one operation, having same name
of the methods increases the readability of the program.
In this example, we have created two methods. The first add() method performs
addition of two numbers and second add method performs addition of three numbers.
Program 4:
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
Output
22
33
Program 5:
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}
Output
22
24.9
Conclusion: Hence we have studied how to define class, methods, object & method
overloading in java