Object Classes Methods and Constructors
Object Classes Methods and Constructors
Object Definitions:
An object is a real-world entity.
An object is a runtime entity.
The object is an entity which has state and behavior.
The object is an instance of a class.
What is a class in Java
class <class_name>
{
field;
method;
}
Class is a keyword in java. <class_name> can be replaced by name of the
class we want to give.
Syntax to declare an object using new
keyword
Class_name object_name = new class_name();
For example:
rectangle r = new rectangle(); // for single object
rectangle r1 = new rectangle(), r2= new rectangle(); // for two objects
• In java object is just a reference variable for accessing
members of the class.
• An object is an instance of a class. You use the new operator
to create an object, and the dot operator (.) to access
members of that object through its reference variable.
Object and Class Example: main within the
class
//Java Program to illustrate how to define a class and fields
//Defining a Student class.
class Student{
//defining fields
int id;
String name;
public static void main(String args[])
{
Student s1=new Student();//creating an object of Student
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
Output
0
null
Object and Class Example: main outside the
class
class Student{
int id;
String name;
}
//Creating another class Example which contains the main method
class Example{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Now your file name should be same as that of class name in which main
method is defined.
Method in Java
Making programs modular and reusable is one of the central
goals in software engineering. Java provides many powerful
constructs that help to achieve this goal. Methods are one such
construct.In Java, a method is like a function which is used to
expose the behavior of an object.
Advantage of Method
Code Reusability
We will discuss methods in more detail after few slides
Ways to initialize object
There are 3 ways to initialize object in Java.
By reference variable
By method
By constructor
By reference variable
class Student{
int id;
String name;
}
class Example
{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name=“rohit";
System.out.println(s1.id+" "+s1.name);
}
}
Initialization through method
class Student{ class TestStudent4
int rollno; {
String name; public static void main(String args[]
void insertRecord(int r, String n) ){
{ Student s1=new Student();
rollno=r; Student s2=new Student();
name=n; s1.insertRecord(111,"Karan");
} s2.insertRecord(222,"Aryan");
void displayInformation() s1.displayInformation();
{ s2.displayInformation();
System.out.println(rollno+" "+name); }
} }
}
Initialization through a constructor
class Example
{
int max (int a,int b)
{
return (a>b?a:b);
}
public static void main(String[] args)
{
Example ob = new Example();
System.out.println("Maximum of 12 and 34 is "+ ob.max(12,34));
}
}
// Defining a static method with in the class in which main method is defined.
// When a method is defined as static method with in the same class in
which // main method is defined. We need not to create object to call that
method.
class Example
{
static int max (int a,int b)
{
return (a>b?a:b);
}
public static void main(String[] args)
{
System.out.println("Maximum of 12 and 34 is "+ max(12,34));
}
}
Example of methods defined in the separate class
class Rectangle{ class TestRectangle1{
int length; public static void main(String args[])
int width; {
void insert(int l, int w)// method Rectangle r1=new Rectangle();
{ Rectangle r2=new Rectangle();
length=l; r1.insert(11,5);
width=w; r2.insert(3,15);
} r1.calculateArea();
void calculateArea() // method r2.calculateArea();
{ }
System.out.println(length*width); }
}
}
Calling method using anonymous
objects
Anonymous objects are the objects that are
instantiated but are not stored in a reference
variable.
• They are used for immediate method calling.
• They will be destroyed after method calling.
Example
class factorial class Example
{ {
public static void main(String[] args)
double calculate(double x) {
{ double f= new factorial().calculate(5);
double i,f=1; System.out.println(f);
for(i=1;i<=x;i++) }
f*=i; }
return f;
}
}
Exercise
Write a program to create a class BankAccount having
instance variable balance.Implement a method deposit(int
amt) which receives the amount to be deposited as an
argument and adds to the current balance.
Implement another method int withdraw() which asks the
user to enter the amount to be withdrawn and updates the
balance if having sufficient balance and return the new
balance. Invoke both the methods from TestBankAccount
class.
Call by Value and Call by Reference in Java
class Example
{
int data=50;
void change(Example op)
{
op.data=op.data+100;//changes will be in the instance variable
}
public static void main(String args[])
{
Example op=new Example();
System.out.println("before change "+op.data);
op.change(op);//passing object
System.out.println("after change "+op.data);
}
}
Passing Array to method(1D)
When passing an array to a method, the reference of the array is passed to the method .
public class Main
{
static int method(int arr[])
{
int sum=0;
for(int i=0;i<arr.length;i++)
{
sum=sum+arr[i];
}
return sum;
}
public static void main(String[] args) {
int a[]={1,2,3,4,5};
System.out.println("Sum of array elements is:"+method(a));
}
}
Passing anonymous array to a method(1D)[Anonymous array means
without creating reference for array]
public class Main
{
static int method(int arr[])
{
int sum=0;
for(int i=0;i<arr.length;i++)
{
sum=sum+arr[i];
}
return sum;
}
public static void main(String[] args) {
System.out.println("Sum of array elements is:"+method(new int[]{1,2,3,4,5}));
}
}
Passing Array to a method(2D)
public class Main
{
static int method(int arr[][])
{
int sum=0;
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr[i].length;j++)
{
sum=sum+arr[i][j];
}
}
return sum;
}
public static void main(String[] args) {
int a[][]={{1,2},{3,4}};
System.out.println("Sum of array elements is:"+method(a));
}
}
Returning array from a method[1D]
public class Main
{
static int[] method()
{
int a[]={1,2,3,4,5};
return a;
}
public static void main(String[] args) {
int arr[]=method();
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
}
Returning array from a method[2D]
public class Main
{
static int[][] method()
{
int a[][]={{1,2},{3,4}};
return a;
}
public static void main(String[] args) {
int arr[][]=method();
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr[i].length;j++)
System.out.println(arr[i][j]);
}
}
}
Using varargs to pass variable number of arguments to a method
// Java program to demonstrate varargs
public class Main
{
// A method that takes variable number of integer arguments.
static void fun(int ...a)
{
System.out.println("Number of arguments: " + a.length);
// using for each loop to display contents of a
for (int i: a)
System.out.print(i + " ");
System.out.println();
}
public static void main(String args[])
{
// Calling the varargs method with different number
// of parameters
fun(100); // one parameter
fun(1, 2, 3, 4); // four parameters
fun(); // no parameter
}
}
Output:
Number of arguments: 1
100
Number of arguments: 4
1234
Number of arguments: 0
Method Overloading
• 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.
• Advantage of method overloading
Method overloading increases the readability of the program.
Different ways to overload the method
• There are two ways to overload the method in java
By changing number of arguments
By changing the data type
• Note: Methods are never overloaded by just changing their return
types
Example 1(Changing no. of arguments)
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
Example 2(Changing data type of arguments)
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
Note: In java, method overloading is not possible by changing
the return type of the method only because of ambiguity. Let's
see how ambiguity may occur:
class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}
Output:
Compile Time Error: method add(int,int) is already defined in class Adder
Method Overloading and Type Promotion
// Data Fields…
// Constructor
public ClassName()
{
// Method Body Statements initialising Data Fields
}
Invoking:
◦ There is NO explicit invocation statement needed: When
the object is created, the constructor method will be
executed automatically.
Constructors
• Constructor name is class name. A constructors must have
the same name as the class its in.
class Example
class rectangle
{
{
public static void main(String[] args) {
int l,b;
rectangle r1 = new rectangle(12,34), r2= new
rectangle(int x,int y)
rectangle(34,56);
{
System.out.println(r1.area());
l=x;
System.out.println(r2.area());
b=y;
}
}
}
int area()
{
return l*b;
}
}
Constructor Overloading
Constructor overloading in Java is a technique of having
more than one constructor with different parameter lists.
They are arranged in a way that each constructor
performs a different task. They are differentiated by the
compiler by the number of parameters in the list and their
types.
Example of constructor overloading
class Example
class sum
{
{
public static void main(String[] args)
sum(int x,int y) {
{ sum s1 = new sum(12,34);
System.out.println("Sum of 2 integers are "+(x+y));
sum s2 = new sum(12,34,67);
}
sum s3 = new sum(12.56,34.78);
sum(int x,int y,int z)
}
{
}
System.out.println("Sum of 3 integers are "+(x+y+z));
}
sum(double x,double y)
{
System.out.println("Sum of 2 doubles are "+(x+y));
}
}
Let’s Do Some thing
Write a program to create a class named Patient which contains:
a. Attributes patient _name, age, contact_number
b.Constructor to initialize all the patient attributes
c. A method to display all the details of any patient
Create a Patient object and display all the details of that patient.
Q1
class Test {
int i;
}
public class Main {
public static void main(String args[]) {
Test t = new Test();
System.out.println(t.i);
}
}
A.-1
B. 0
C. Compiler error
D. Runtime error
Q2
class Test {
int i;
}
pubic class Main {
public static void main(String args[]) {
Test t;
System.out.println(t.i);
}
A. 0
B. -1
C. Compiler error
D. Runtime error
public class Main
Q3
{
static void modify(int a)
{
a=a+12;
}
public static void main(String[] args) {
int x=12;
modify(x);
System.out.println(x);
}
}
A. 24
B. 12
C. 0
D. Compile time error
Q4
public class Main
{
A. 13 15
int a,b;
static void modify(Main obj)
B. 15 17
{ C. 0 0
obj.a=obj.a+2;
obj.b=obj.b+2; D. 1 1
}
public static void main(String[] args) {
Main o1=new Main();
o1.a=13;
o1.b=15;
modify(o1);
System.out.println(o1.a+" "+o1.b);
}
}
class Dummy
Q5
{
static void show()
{
System.out.println("Hello");
}
}
public class Main
{
public static void main(String[] args) {
show();
}
}
A. Hello
B. Compile time error
C. Runtime error
D. Nothing will be displayed