You are on page 1of 68

Chapter 2:-

CLASSES,OBJECTS&
METHODS

Compiled By:- Diksha Durgapal


Assistant Professor,
ITMBU
Classes & Objects
3

 Object - Objects have states and behaviors.


Example: A dog has states-color, name, breed as
well as behaviors -wagging, barking, eating. An
object is an instance of a class.
 Class - A class can be defined as a template/ blue
print that describe the behaviors/states that object
of its type support.
Class
4

 In object-oriented programming, a class is a programming


language construct that is used as a blueprint to create objects.
 This blueprint includes attributes and methods that the created
objects all share.
 Usually, a class represents a person, place, or thing - it is an
abstraction of a concept within a computer program.
 Fundamentally, it encapsulates the state and behavior of that
which it conceptually represents.
 It encapsulates state through data placeholders called member
variables; it encapsulates behavior through reusable code
called methods.
Class-syntax
5

class classname{
type instance_variable1;
type methodname1(parameter_list)
{
//body of mehod
}
type methodname2(argument_list)
{
//body of method
}
}
Declaring Class
6

class classname { public class Dog


type instance-variable1; {
type instance-variable2; String breed;
// ... int age;
type instance-variableN; String color;
type methodname1(parameter-list) {
// body of method void barking()
} {
type methodname2(parameter-list) { }
// body of method void hungry()
} {
// ... }
type methodnameN(parameter-list) { void sleeping()
// body of method {
} }
} }
Objects
7

 An Object is a real time entity. An object is an


instance of a class. An object will have some
properties and it can perform some actions.
 Object contains variables and methods. The objects
which exhibit similar properties and actions are
grouped under one class. “To give a real world
analogy, a house is constructed according to a
specification.
Creating object (New operator)
8

 Toaccessthe properties and methods of a class,we must


declare a variable of that class type. This variable does not
define an object. Instead, it is simply a variable that can refer
to an object.
 We must acquire an actual, physical copy of the object and
assign it to that variable. We can do this using new operator.
The new operator dynamically allocates memory for an
object and returns a reference to it. Thisreference is, more or
less, the address in memory of the object allocated by new.
 This reference is then stored in the variable. Thus, in Java, all
class objects must be dynamically allocated.
new operator

• Using the new keyword in java is the most basic way


to create an object. This is the most common way to
create an object in java.
• By using this method we can call any constructor we
want to call (no argument or parameterized
constructors).
• Example:
mybox = new Box();
Declaring Object
9

Box mybox = new Box(); // create a Box object called mybox

Box mybox; // declare reference to object


mybox = new Box(); // allocate a Box object
Example of Class
10

class Box
{
double width;
double height; Instance Variable
double depth;
}
The new operator dynamically allocates memory for an object.

Box mybox = new Box(); // create a Box object called mybox

mybox is an instance(object) of Box


Example of class and object
class Student
{
int rollNo; //properties -- variables
String name;
void display () //method -- action
{
System.out.println ("Student Roll Number is: " + rollNo);
System.out.println ("Student Name is: " + name);
}
}
The dot(.) operator links
class StudentDemo the name of the object with
{ the name of an instance
public static void main(String args[]) variable.
{
Student s = new Student (); / / create an object to Student class
s.display (); / / call display () method inside Student class using object s
}
} Ankit Shah
Output
12
Example Instance variable
class Student
{
int rollNo = 101;
String name = “Surya“;
void display ()
{
System.out.println ("Student Roll Number is: " + rollNo);
System.out.print ("Student Name is: " + name);
}
}
class StudentDemo
{ public static void main(String args[])
{ Student s1 = new Student ();
System.out.println ("First Student Details : " );
s1.display ();
Student s2 = new Student ();
System.out.println ("Second Student Details : " );
s2.display ();
} Ankit Shah
}
Output
14
Another Example
class Box {
double width;
double height;
double depth;
}
/ / This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
/ / assign valuesto mybox'sinstance variables
The dot(.) operator links
mybox.width = 10; the name of the object with
mybox.height = 20; the name of an instance
mybox.depth = 15; variable.
/ / compute volume of box
double vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
} Volume is 3000.0
Ankit Shah
Difference Between Objects and Classes
16

 It is fact that the difference between classes and


objects is often the source of some confusion.
 But we can say that, Classes have logical existence,
whereas objects have physical existence
 For example, furniture itself does not have any
physical existence, but chair, table etc. do have
physical existence.
The OOP Principles
17

 Abstraction
 Encapsulation
 Inheritance
 Polymorphism
Abstraction
18

 Providing the essential features without its inner details is


called abstraction (or) hiding internal implementation is called
Abstraction.
 We can enhance the internal implementation without effecting
outside world. Abstraction provides security.
 A class contains lot of data and the user does not need the
entire data.
 The advantage of abstraction is that every user will get his
own view of the data according to his requirements and will
not get confused with unnecessary data.
Abstraction- Example
19

Public abstract class Bank


{
private int accno;
private String name;
private float balance;
private float loan;
void display_to_cler ()
{
System.out.println ("Accno = " + accno);
System.out.println ("Name = " + name);
}
}
Encapsulation
20

 Encapsulation is one of the four fundamental OOP


concepts.
 The wrapping of Data and Methods into a single unit
(called class) ika Encapsulation.
 Encapsulation is the technique of making the fields in a
class private and providing access to the fields via public
methods.
 If a field is declared private, it cannot be accessed by
anyone outside the class, thereby hiding the fields within
the class. For this reason, encapsulation is also referred to
as data hiding.
Cont‟d…
21

 Encapsulation can be described as a protective


barrier that prevents the code and data being
randomly accessed by other code defined outside
the class. Access to the data and code is tightly
controlled by an interface.
 The main benefit of encapsulation is the ability to
modify our implemented code without breaking the
code of others who use our code. With this feature
Encapsulation gives maintainability, flexibility and
extensibility to our code.
Example
22
Example
23

public class Encap{ public class Encapsul


private String name; {
private int age; public static void main(String args[])
public int getAge(){ {
return age; } Encap en = new Encap();
public String getName(){ return name; en.setName("James");
} en.setAge(20);
public void setAge( int newAge) System.out.print("Name : "+
{ age = newAge; } en.getName()+ "Age : "+ en.getAge());
public void setName(String newName) }
{ name = newName; } }
}
Inheritance
24

 Inheritance can be defined as the process where


one object acquires the properties of another. With
the use of inheritance the information is made
manageable in a hierarchical order.
 When we talk about inheritance the most commonly
used keyword would be extends and implements.
 These words would determine whether one object
IS-A type of another. By using these keywords we
can make one object acquire the properties of
another object.
Example
25
Types of inheritance
26
Example
27

class Parent
{
String parentName;
String familyName;
}
class Child extends Parent
{
String childName;
int childAge;
void printMyName()
{
System.out.println (“My name is“+childName+” ”+familyName);
}
Polymorphism
28

 Polymorphism is the ability of an object to take on many forms.


The most common use of polymorphism in OOP occurs when a
parent class reference is used to refer to a child class object.
 Any java object that can pass more than one IS-A test is
considered to be polymorphic. In Java, all java objects are
polymorphic since any object will pass the IS-A test for their
own type and for the class Object.
 It is important to know that the only possible way to access an
object is through a reference variable. A reference variable
can be of only one type. Once declared the type of a
reference variable cannot be changed.
Example
29
Example
30

int add (int a, int b)


float add (float a, int b)
float add (int a , float b)
void add (float a)
int add (int a)
Access Control & Modifiers
The members of a class have their visibility in the same class or
other classes. The classes have their associated accessibility.
How and where a member of a class is accessed is determined by
the access specifiers.
The access specifiers in java are:
1. public: When a class member is declared with the public access
specifiers, it can be accessed from anywhere in the program.
The public classes,methods, or fields are used only if you
explicitly want to offer access to these members.
2. private: You can access the private methods and fields only
within the same class to which the methods and fields belong.
When you declare a method or field as private, it is not visible
within the subclasses and is not inherited by the subclasses.
Access Control & Modifiers

3. protected: You can access the protected methods and fields


from within the same class to which the methods and fields
belong, within its subclasses, and within the classes of the
same package, but not from other packages. The protected
access specifier cannot be used with class declaration
4. Default: If you do not specify any access specifier while
declaring class, method or field then they are considered with
default access specifier. The class, method or field with default
access specifier can be accessed from within the same package
to which they belongs. These are not accessible outside the
package it belong
Introducing Methods
31

 A Java method is a collection of statements that are


grouped together to perform an operation.
 When you call the System.out.println method, for
example, the system actually executes several
statements in order to display a message on the
console.
This is the general formof a method:
type name(parameter-list) {
/ / body of method
}
Cont‟d…
32

 Here, type specifies the type of data returned by the method.


This can be any valid type, including class types that you
create.
 If the method does not return a value, its return type must be
void. The name of the method is specified by name. This can
be any legal identifier other than those already used by other
items within the current scope.
 The parameter-list is a sequence of type and identifier pairs
separated by commas. Parameters are essentially variables
that receive the value of the arguments passed to the method
when it is called.
 If the method has no parameters, then the parameter list will
be empty
Why method?
33

 The word method is commonly used in object-


oriented programming. It is similar to a function in
any other programming language.
 Name of method can be declared outside the class.
All methodshave a name that starts with a
lowercase character.
Cont‟d..
34

 To make code reusable: If we need to do the same thing or


almost the same thing, many times ,write a method to do it and
then call the method each time you have to do the task.
 To parameterize the code:-We will often use parameters to
change the way the methods behaves.
 For top-down programming:-We can easily solve a bigger
problem or a complex one by breaking it into smaller parts.
For the same purpose, we write methods. The entire complex
problem can be broken down into methods.
 To simplify the code:-Because the complex code inside a
methods is hidden from other parts of the program, it prevents
accidental errors or confusion.
class Box { class Boxdemo {
double width; public static void main(String args[]) {
double height; Box mybox1 = new Box();
double depth; Box mybox2 = new Box();
double vol;
// compute and return // initialize each box
volume mybox1.setDim(10, 20, 15);
double volume() { mybox2.setDim(3, 6, 9);
return width * height * depth; // get volume of 1st box
} vol = mybox1.volume();
// display volume of a box System.out.println("Volume is " + vol);
void volume1() { // get volume of 2nd box
System.out.print("Volume is "); vol = mybox2.volume();
System.out.println(width * height * depth); System.out.println("Volume is " + vol);
} mybox1.volume1();
// sets dimensions of box // display volume of 2nd box
void setDim(double w, double h, double d) mybox2.volume1();
{ }
width = w; }
height = h;
depth = d;
}
}
Method Overloading
36

 If two methods have the same name but different


parameter lists within one class is called “Method
Overloading”.
 Overloaded methods must have different
parameter lists. You cannot overload methods
based on different modifiers or return types.
 When overloaded methods are used, the java
compiler decides which method is to be
invoked by the number and/or types of
parameters you pass to the method.
class Box { class met
double width; {
double height; public static void main(String args[])
double depth; {
double volume() { Box mybox1 = new Box();
return width * height * depth; Box mybox2 = new Box();
} // initialize each box
double volume1() { mybox1.setDim(10, 20, 15);
return width * height; mybox2.setDim(3, 6);
} // get volume of first box
void setDim(double w, double h, double d) double vol = mybox1.volume();
{ System.out.println("Volume is " + vol);
width = w; // get volume of second box
height = h; vol = mybox2.volume1();
depth = d; System.out.println("Volume is " + vol);
} }
void setDim(double w, double h) { }
width = w;
height = h;
}
}
Recursion

• Each time a method is called, a new space is allocated on


the internal stack for all the variable in the method, which
means there is no reason you can’t call the same method
again – a new set of variables will be allocated on the stack
automatically
• Recursion is a technique in which a method calls itself.
• This technique provides a way to break complicated
problems down into simple problems which are easier to
solve.
• Examples of recursion are:
• Factorial of number
• Fibonacci series
Recursion

Syntax:

type methodname(){
//code to be executed
methodname();//calling same method
}

Example:
void demo(){
System.out.println(“hello”);
demo();
}
Recursion Example

public class Recursion {


static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}

public static void main(String[] args) {


System.out.println("Factorial of 5 is: "+factorial(5));
}
}
Constructors
38

 A constructor is similar to a method that initializes


the instance variables of a class.
 A constructor havethesamenameastheclassname.
 A constructor may have or may not have
parameters. Parameters are local variables to
receive data.
 Once defined, the constructor is automatically
called immediately after the object is created,
before the new operator completes.
Cont‟d…
39

 A constructor without any parameters iscalled default


constructor.
 A constructor with one or more parameters is called
parameterized constructor.
 A constructor does not return any value, not even void
because implicitly the return type of a constructor is
the class itself.
 A constructor is called only once per object.
No-argument constructor

Similar to methods, a Java constructor may or may not


have any parameters (arguments).
If a constructor does not accept any parameters, it is
known as a no-argument constructor.

Syntax:

constructor()
{
//syntax
}
No argument Constructor
class Main {
int i;
private Main() {
i = 5;
System.out.println("Constructor is called");
}
public static void main(String[] args) {
Main obj = new Main();
System.out.println("Value of i: " + obj.i);
}
}

Ankit Shah
Default Constructor

If we do not create any constructor, the Java compiler


automatically create a no-argument constructor during the
execution of the program. This constructor is called default
constructor.

Default constructorisusedto initialize every object with same data.

Syntax:
Constructorname(){
//statements
}
Example Default Constructor
class Student
{ int rollNo;
String name;
Student ()
{ rollNo = 101;
name = "Suresh";
}
void display () {
System.out.println ("Student Roll Number is: " + rollNo);
System.out.println ("Student Name is: " + name);
}
}
class StudentDemo { public static void main(String args[])
{ Student s1 = new Student ();
System.out.println ("s1 object contains: ");
s1.display ();
Student s2 = new Student ();
System.out.println ("s2 object contains: ");
s2.display
Ankit();
Shah}}
Parameterized Constructor

A Java constructor can also accept one or more parameters. Such


constructors are known as parameterized constructors
(constructor with parameters).

Parameterized constructor is used to initialize each object with different


data.

Syntax:
constructor(parameters)
{
//statements
}
Parameterized Constructor
class Main {
String languages;
Main(String lang) {
languages = lang;
System.out.println(languages + " Programming
Language");
}

public static void main(String[] args) {


Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
} Ankit Shah
Constructor Overloading

The constructor overloading can be defined as the


concept of having more than one constructor with
different parameters so that every constructor can
perform a different task.
class Box { class BoxDemo6
double width; {
double height; public static void main(String args[])
double depth; {
// This is the constructor for Box. // declare, allocate, and initialize Box obj
Box() { Box mybox1 = new Box();
width = 10; Box mybox2 = new Box(10,20,15);
height = 10; double vol = mybox1.volume();
depth = 10; System.out.println("Volume is " + vol);
} // get volume of second box
// This is the constructor for Box. vol = mybox2.volume();
Box(double w, double h, double d) { System.out.println("Volume is " + vol);
width = w; }
height = h; }
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth; Output
} Volume is 1000.0
} Volume is 3000.0
The this Keyword
44

 There will be situations where a method wants to refer to the


object which invoked it.
 To perform this we use this keyword. There are no restrictions to
use this keyword we can use this inside any method for referring
the current object.
 This keyword is always a reference to the object on which the
method was invoked. We can use this keyword wherever a
reference to an object of the current class type is permitted.
this is a key word that refers to present class object.
🞑 Present class instance variables
🞑 Present class methods.
🞑 Present class constructor.
The this Keyword
44

• Following are various uses of ‘this’ keyword in Java:


• It can be used to refer instance variable of current
class
• It can be used to invoke or initiate current class
constructor
• It can be passed as an argument in the method
call
• It can be passed as argument in the constructor
call
• It can be used to return the current class instance
Example “this” Keyword
class Person
{ String name;
Person ( )
{
this (“Ravi Sekhar”); / / calling present class parameterized constructor
this.display ( ); / / calling present class method
}
Person (String name)
{
this.name = name; / / assigning present class variable with parameter “name”
}
void display( )
{ System.out.println ("Person Name is = " + name); }}
class ThisDemo
{
public static void main(String args[])
{
Person p = new Person ( );
} Ankit Shah
}
Output
46
Static keyword

• In Java, static keyword is mainly used for memory


management. It can be used with variables, methods,
blocks and nested classes.
• It is a keyword which is used to share the same variable
or method of a given class.
• Basically, static is used for a constant variable or a
method that is same for every instance of a class. The
main method of a class is generally labeled static.
Static keyword

• Static methods can only access and modify static


variables.
• Static methods can be called/used without creating a
class instance.
Example
class Person{ Output
static int age;
}
class Main{
public static void main(String args[]){
Person p1 = new Person();
Person p2 = new Person();
p1.age = 30;
p2.age = 31;
Person.age = 32;
System.out.println("P1\'s age is: " + p1.age);
System.out.println("P2\'s age is: " + p2.age);
}
}
this & static

• The static methods belong to the class and they will


be loaded into the memory along with the class.
You can invoke them without creating an object.
• The "this" keyword is used as a reference to an
instance.
• Since the static methods doesn’t belong to any
instance you cannot use the "this" reference within
a static method.
Example

class demothisstatic{
static int num = 50;
public static void demo(){
System.out.println("Contents of the static
method"+this.num);
}
public static void main(String args[]){
demothisstatic.demo();
}
}
Garbage Collection
47

 Since objects are dynamically allocated by using the new


operator, you might be wondering how such objects are
destroyed and their memory released for later reallocation.
 In some languages, such as C++, dynamically allocated
objects must be manually released by use of a delete
operator.
 Java takes a different approach; it handles deallocation for
you automatically. The technique that accomplishes this is
called garbage collection.
 It works like this: when no references to an object exist, that
object is assumed to be no longer needed, and the memory
occupied by the object can be reclaimed.
Cont‟d…
48

 There is no explicit need to destroy objects as in C++.


 Garbage collection only occurs sporadically (if at all)
during the execution of your program.
 It will not occur simply because one or more objects
exist that are no longer used. Furthermore, different
Java run-time implementations will take varying
approaches to garbage collection, but for the most
part, you should not have to think about it while
writing your programs.
Advantages of Garbage Collection
49

 Garbage Collection eliminates the need for the


programmer to de allocate memory blocks
explicitly
 Garbage collection helps ensure program integrity.
 Garbage collection can also dramatically simplify
programs.
Disvantages of Garbage Collection
50

 Garbage collection adds an overhead that can


affect program performance.
 Garbage Collection requires extra memory.
 Programmers have less control over the scheduling
of CPU time.
The finalize() method
51

 It is possible to define a method that will be called


just before an object's final destruction by the
garbage collector.
 This method is called finalize( ) method. To add a
finalizer to a class, simply define the finalize()
method.
 The Java runtime calls that method whenever it is
about to recycle an object of that class. Inside the
finalize( ) method specify those actions that must be
performed before an object is destroyed.
Cont‟d..
52

 The finalize( ) method has this general form:


protected void finalize( )
{
/ / finalization code here
}
 It is important to understand that finalize( ) is only
called just prior to garbage collection.
 It is not called when an object goes out-of-scope.
Inbuilt classes
55

 String :- java.lang.String
 Character :- java.lang.Character
 StringBuffer :- java.lang.StringBuffer
 File class :- java.io

You might also like