0% found this document useful (0 votes)
3 views

Chapter-7

Uploaded by

xaeabhishek
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter-7

Uploaded by

xaeabhishek
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

CHAPTER:7: -CLASSES, OBJECT AND METHOD-1

Object:-
 An object in Java is the physical as well as a logical entity, 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 .
 An object has three characteristics:

 State: represents the data (value) of an object.


 Behavior: represents the behavior (functionality) of an object such as deposit, withdraw,
etc.
 Identity: An object identity is typically implemented via a unique ID. The value of the ID
is not visible to the external user. However, it is used internally by the JVM to identify
each object uniquely.

 For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It
is used to write, so writing is its behavior.

 An object is an instance of a class. A class is a template or blueprint from which objects


are created. So, an object is the instance(result) of a class.
 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.

Class:-
 A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created. It is a logical entity. It can't be physical.
 A class in Java can contain:

 Fields
 Methods
 Constructors
 Blocks

Prepared By:-Ankur Patel


 Nested class and interface

 Syntax to declare a class:

class <class_name>
{
field;
method;
}

Instance variable in Java


 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.

new keyword in Java


 The new keyword is used to allocate memory at runtime. All objects get memory in Heap
memory area.
 Heap Memory is used for Dynamic Memory Allocation of Java objects and JRE classes that
are created during the execution of a Java program. Heap memory is allocated to objects at
runtime and these objects have global access which implies they can be accessed from
anywhere in the application.

Object and Class Example: main method within the class


Example:1
 In this example, we have created a Student class which has two data members id and name.
We are creating the object of the Student class by new keyword and printing the object's
value.
 Here, we are creating a main() method inside the class.
//Java Program to illustrate how to define a class and fields
//Defining a Student class.
class Student
{
//defining fields
int id; //field or data member or instance variable

Prepared By:-Ankur Patel


String name; //field or data member or instance variable
//creating main method inside the Student class
public static void main(String args[])
{
//Creating an object or instance
Student s1=new Student(); //creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
Output:
0
null
Object and Class Example: main method in a Separate class
Example:2
 In this example we are going to initialize the object through a reference variable.
 Here we are Creating “main ()” method in a separate(different) class
class Student
{
int id;
String name;
}
class TestStudent2
{
public static void main(String args[])
{
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name) ;//printing members with a space
}
}
Output:

Prepared By:-Ankur Patel


101 Sonoo
Example:3
 We can also create multiple objects and store information in it through reference variable.

class Student
{
int id;
String name;
}
class TestStudent3
{
public static void main(String args[])
{
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}

SeeSee
below figure
below is represented
figure graphically
is represented for how
graphically fortohow
memory occupyoccupy
to memory by obj1by
and obj2.
obj1 and obj2.
int a; int a;
Obj1 Obj2
int b; int b;

int c; int c:

(a) Memory occupy by object1 (b) Memory occupy by object2

Prepared By:-Ankur Patel


Method in Java
 In Java, a method is like a function which is used to expose the behavior of an object.
 A method is a set of code which is referred to by name and can be called (invoked) at any
point in a program. Think of a method as a subprogram that acts on data and often returns a
value.
 Each method has its own name. Then that name is encountered in a program, the execution
of the program branches to the body of that method.
 When the method is finished, execution returns to the area of the program code from which
it was called, and the program continues on to the next line of code.

Advantage of Method

 Code Reusability
 Code Optimization

 There are two basic types of methods:


 Built-in :Built-in Method are part of the complier package, Example: System.out.println
() and System.exit (0).
 User Define: User defines Method are created by user or programmer. These methods
takes on name that you assign to them and perform tasks that programmer created.

Prepared By:-Ankur Patel


The Structure of a Method

 The method visibility modifier goes first. Here in above example it is public.
 Then method's return type goes second, which is void type in the code above.
 After the method type, you need a space followed by the name of your method.
We've called the one above sum.
 In between a pair of round brackets we have told Java that is parameter List. Here we have
used two variable which names are a and b respectively.
 To separate this method from any other code, you need a pair of curly brackets. Your code
for the method goes between the curly brackets. Then here we have used those variables
which are passed in the parameter. And remember it here we have not return any value so
we do not wrought return statements.

Prepared By:-Ankur Patel


 If sometimes we have needed something to return from our method. Then see
below figure.

 How to Create an Object and Called User define Method:


 Before we called java methods, we need an Object. So first we have need
creation of an Object. As you know, a class provides the blueprint for objects;
you create an object from a class.

 Let’s now we will discuss about all four step see in above figure.
 Step 1: create an Object. Here class name is DemoMethod and d1 is an Object name.
 Step 2: this step is indication of how to call method using an Object. Here
sum is method name and values 10 and 20 are as parameters.

Prepared By:-Ankur Patel


 Step 3: this step is indicated that is a Method body. When we called user define
method using an object then control goes on function body.
 Step 4: after finished execution of all statements in method body then control will
back to main method with return value.
 Return value is not compulsory. It is depend on user logic.

Initialization of object through method (Method with parameters:)


 In this example, we are creating the two objects of Student class and initializing the value
to these objects by invoking the get() method. Here, we are displaying the state (data) of
the objects by invoking the display() method.
class Student
{
int rollno;
String name;
void get(int r, String n) Formal Parameters
{
rollno=r;
name=n;
}
void display()
{
System.out.println(rollno+" "+name);}
}
class TestStudent
{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.get(111,"Karan");
Actual Parameters
s2.get(222,"Aryan");
s1.display();
s2.display();
}
}

Prepared By:-Ankur Patel


Example:
class Demo
{
void sum(int x, int y)
{
System.out.println("addition is="+ (x+y));
}
void sub(intx, int y)
{
System.out.println("subtraction is="+ (x-y));
}
void mul(int x, int y)
{
System.out.println("multiplication is="+ (x*y));
}
void div(int x, int y)
{
System.out.println("division is="+ (x/y));
}
Class Main
{
public staticvoid main(String [] args)
{
Demo d1=new Demo();
d1.sum(50,30);
d1.sub(50, 30);
d1.mul(50, 30);
d1.div(50, 30);
}
}
Output:
addition is=80
subtraction is=20
multiplication is=1500

Prepared By:-Ankur Patel


Method with a Return Type
 When sometime method returns some value that is the return-type of that method,
For Example: sometimes method is takes arguments but does not return any things,
so that method has return type is void. If method returns integer value then the return-type
of method is an integer.
 Following program shows the method with their return type.

Example:
class Demo
{
int sum(int x, int y)
{
return(x+y);
}
int sub(intx, int y)
{
return(x-y);
}
int mul(int x, int y)
{
return(x*y);
}
double div(double x, double y)
{
return(x/y);
}
Class Main
{
public static void main(String [] args)
{
Demo d1=new Demo();
int ans1,ans2,ans3,ans4;
ans1=d1.sum(50,30);
ans2=d1.sub(50, 30);
ans3=d1.mul(50, 30);

Prepared By:-Ankur Patel


ans4=d1.div(50.0, 25.0);
System.out.println("Addition is="+ans1);
System.out.println("Subtraction is="+ans2);
System.out.println("multiplication is= "+ans3);
System.out.println("Division is="+ans4);

}
}
Output:
Addition is=80
Subtraction is=20
Multiplication is=1500
Division is=2.0

There are Four categories of Method:


(a) No arguments (parameters) and No return value.
(b) With argument but No return value.
(c) With arguments and return value.
(d) Without arguments and with return value.

(a) No arguments (parameters) and No return value.

 Example 1: sum of two numbers


class Demo
{
void sum()
{
int a=10,b=20;
int ans;
ans=a+b;
System.out.println("Sum of A and B =" + ans);
}
}
class Main
{
publicstaticvoid main(String[] args)
{
Demo d1=new Demo();
d1.sum();
}

Prepared By:-Ankur Patel


}

(b) With argument but No return value.


 Example 2: sum of two numbers
class Demo
{
void sum(int a, int b)
{
int ans;
ans=a+b;
System.out.println("Sum of A and B =" + ans);
}
}
class Main
{
public static void main(String[] args)
{
Demo d1=new Demo();
d1.sum(10,20);
}
}

(c) With arguments and return value.


 Example 3: sum of two numbers
class Demo
{
int sum(int a, int b)
{
int ans;
ans=a+b;
return(ans);
}
}
class Main
{
public static void main(String[] args)
{
Demo d1=new Demo();
int ans1;
ans1=d1.sum(10,20);
System.out.println("Sum of A and B =" + ans1);

Prepared By:-Ankur Patel


}

(d) Without arguments and with return value.


 Example 4: sum of two numbers
class Demo
{
int sum()
{
int a=10,b=20;
int ans;
ans=a+b;
return(ans);
}
}
class Main
{
public static void main(String[] args)
{
Demo d1=new Demo();
int ans1;
ans1=d1.sum();
System.out.println("Sum of A and B =" + ans1);

}
}

Recursion in Java
 Recursion in java is a process in which a method calls itself continuously. A method in
java that calls itself is called recursive method.
 It makes the code compact but complex to understand.
 Syntax:
returntype methodname()
{
//code to be executed
methodname();//calling same method
}

Prepared By:-Ankur Patel


 Java Recursion Example 1: Infinite times

class RecursionExample1
{
void p()
{
System.out.println("hello");
p();
}

public static void main(String[] args)


{
RecursionExample1 re=new RecursionExample1();
re.p();
}
}
 Output:

hello
hello
...
java.lang.StackOverflowError

 Java Recursion Example 2: Finite times

class RecursionExample2
{
int count=0;
void p()
{
count++;
if(count<=5)
{
System.out.println("hello "+count);

Prepared By:-Ankur Patel


p();
}
}
public static void main(String[] args)
{
RecursionExample2 re=new RecursionExample2();
re.p();
}
}

 Output:

hello 1
hello 2
hello 3
hello 4
hello 5

 Java Recursion Example 3:To add all of the numbers up to 10.


class Main
{
int sum(int k)
{
if (k > 0)
{
k=k+sum(k - 1);
return(k);
}
else
{
return(0);
}
}
public static void main(String[] args)
{
Main m=new Main();
int result = m.sum(10);
System.out.println(result);
}

Prepared By:-Ankur Patel


}
 Explaination:

sum(10)
sum(9)
sum(8)
sum(7)
sum(6)
sum(5)
sum(4)
sum(3)
sum(2)
sum(1)
Sum(0)
return 0
return 0+1=1
return 1+2=3
return 3+3=6
return 6+4=10
return 10+5=15
return 15+6=21
return 21+7=28
return 28+8=36
return 36+9=45
return 45+10=55

 Java Recursion Example 4:Factorial of a number


class RecursionExample4
{
int factorial(int n)
{
if (n == 1)
{
return (1);
}
else
{

Prepared By:-Ankur Patel


n=n*factorial(n-1);
return(n);
}

}
public static void main(String[] args)
{
RecursionExample4 re=new RecursionExample4();
int fac;
fac=re.factorial(5);
System.out.println("Factorial of 5 is:"+fac);
}
}

Explaination
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120

Prepared By:-Ankur Patel

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy