0% found this document useful (0 votes)
4 views66 pages

503 33 Powerpoint-Slides Chapter-4

Chapter 4 discusses classes and objects in Java, explaining that a class serves as a blueprint for creating objects, which encapsulate data and methods. It covers class declaration syntax, the importance of instance variables, methods, and constructors, as well as concepts like method overloading and constructor overloading. The chapter emphasizes the benefits of modularity, reusability, and data encapsulation in object-oriented programming.

Uploaded by

mahipatil351
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views66 pages

503 33 Powerpoint-Slides Chapter-4

Chapter 4 discusses classes and objects in Java, explaining that a class serves as a blueprint for creating objects, which encapsulate data and methods. It covers class declaration syntax, the importance of instance variables, methods, and constructors, as well as concepts like method overloading and constructor overloading. The chapter emphasizes the benefits of modularity, reusability, and data encapsulation in object-oriented programming.

Uploaded by

mahipatil351
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Chapter 4

Classes and Objects

© Oxford University Press 2013. All rights reserved.


Classes and Objects
• A class is a blueprint or prototype that defines the
variables and methods common to all objects of a
certain kind.
• Class can be thought of as a user defined data type
and an object as a variable of that data type, which
can contain data and methods i.e. functions, working
on that data.
• All object instances have their own copies of
instance variable.
• Each object has its own copy of instance variables
which is different from other objects created out of
the same class.

© Oxford University Press 2013. All rights reserved.


How to declare Class in JAVA?
• A class is declared using class keyword followed by
the name of the class.
• Syntax of declaration of class
class classname {
//Variables declaration
//Methods declaration
}
• Example
class GoodbyeWorld {
public static void main (String args[]) {
System.out.println("Goodbye World!");
}}

© Oxford University Press 2013. All rights reserved.


Declaring classes in Java
• The class declaration can specify more about the class like you
can:
• declare what the class's superclass (discussed in chapter 5)
• list the interfaces implemented by the class (discussed in
chapter 6)
• declare whether the class is public, abstract,( discussed in
chapter 6) or final (discussed in chapter 5)
• Summary of class declaration syntax as;
[modifiers] class ClassName [ extends SuperClassName ] [
implements InterfaceNames ] {
…………
}

© Oxford University Press 2013. All rights reserved.


Declaring classes in Java (contd.)
• The items between [ and ] are optional. A class
declaration defines the following aspects of the class:
– modifiers declare whether the class is public, protected,
default, abstract, or final
– ClassName sets the name of the class you are declaring
– SuperClassName is the name of ClassName's superclass
– InterfaceNames is a comma-delimited list of the interfaces
implemented by ClassName
• The Java compiler assumes the class to be non-final,
non-public, non-abstract, subclass of Object (chapter
6) that implements no interfaces if no explicit
declaration is specified.

© Oxford University Press 2013. All rights reserved.


Parts of a class
• The class contains two different sections:
variable declarations and method declaration.
The variables of a class describe its state and
methods describe its behavior.
classDeclaration {
memberVariableDeclarations
methodDeclarations
}

© Oxford University Press 2013. All rights reserved.


Objects
• The real-world objects have state and behavior.
• For example,
– horses have state (name, color, breed, hungry) and horses
have behavior (fetching, and slobbering on your newly
cleaned slacks).
– Bikes have state (gear, accelerator, two wheels, number of
gears, brakes) and behavior (braking, accelerating, slowing
down and changing gears).
• An object is a software bundle which encapsulates
variables and methods, operating on those variables.

© Oxford University Press 2013. All rights reserved.


Why should we use classes and objects
Modularity and
information hiding i.e.
data encapsulation can
be incorporated using
an object, in software.
Classes, being
blueprints, provide the
benefit of reusability.
Creating Objects
• Java object created with a statement like this one:
SalesTaxCalculator obj1 = new SalesTaxCalculator ( );

• This statement creates a new SalesTaxCalculator


object.
• This single statement declares, instantiates, and
initializes the object.

© Oxford University Press 2013. All rights reserved.


Declaring an Object
• object declarations is same as variable declarations
for e.g.
– SalesTaxCalculator obj1;
• Generally the declaration is as follows:
– type name;
– Where type is the type of the object (i.e. class name) and
name is the name of the reference variable used to refer
the object
• Difference between variables and objects:
– A variable holds a single type of literal, while an
– object is a instance of a class with a set of instance
variables and methods which performs certain task
depending what methods have been defined for .

© Oxford University Press 2013. All rights reserved.


Initializing an object
• By initializing an object we mean that the instances
variables are assigned some values. This task is
accomplished using a constructor.
• The final object creation can be said as complete
when the objects are initialized, either with an
implicit constructor or an explicit constructor. This
object creation can be used in programming code in
two ways:
– SalesTaxCalculator obj1 = new SalesTaxCalculator ( );
• Here all the three operations, object declaration,
object instantiation and object initialization are done
by one statement only.

© Oxford University Press 2013. All rights reserved.


Initializing an object
• The above process actually takes place in
following way:
Assigning Object Reference
Variables
• One object reference can be assigned to another
object reference variable , then the copy of the
object is not created but copy of the reference is
made.
• Eg. Rectangle R1 = new Rectangle ();
• Rectangle R2 = R1;
Instance Variable
• A class can have many instances, each instance having its own
set of variables. E.g.
class SalesTaxCalculator {
float amount=100.0f; // instance variable
float taxRate=10.2f; //instance variable
public static void main (String args[ ]) {
SalesTaxCalculator obj1 = new SalesTaxCalculator();
SalesTaxCalculator obj2 = new SalesTaxCalculator();
System.out.println("Amount in Object 1: "+ obj1.amount);
System.out.println("Tax Rate in Object 1: "+ obj1.taxRate);
System.out.println("Amount in Object 2: "+ obj2.amount);
System.out.println("Tax Rate in Object 2: "+ obj2.taxRate);
}}

© Oxford University Press 2013. All rights reserved.


Instance variable (contd.)
• Each variable declared inside a class and outside the
methods is termed as instance variable (except static
variables), because they are created whenever an
instance (object) of the class is created and these
variables are initialized by the constructors.
• In the above example the two objects obj1 and obj2
will have their own set of instance variables. i.e. obj1
will have its own amount and taxRate whereas obj2
will have its own set of amount and taxRate.

© Oxford University Press 2013. All rights reserved.


Accessing Instance Variables
• For accessing value of an object
– Objectname.variablename
• to assign values to the variables of an object
– Objectname.variablename = value
• There are three ways of assigning values to the
instance variables in the objects:
– Assigning values directly to the instance variables as shown
below,
float amount=100.0f;
– Assigning values through a setter method
– values can be assigned using constructors.

© Oxford University Press 2013. All rights reserved.


Methods
• Methods are similar to a function in any other
programming languages.
• None of the methods can be declared outside the
class.
• Why use methods?
– To make code reusable
– To parameterize code
– For top-down programming
– To simplify code

© Oxford University Press 2013. All rights reserved.


Method (contd.)
• General syntax for a method declaration:
[modifiers] return_type method_name (parameter_list)
[throws_clause] { [statement_list]}
• The method declaration includes:
– Modifiers: The modifiers are optional. They can be, public,
protected, default or private, static, abstract, final, native,
synchronized, throws

© Oxford University Press 2013. All rights reserved.


Optional Modifiers Used with Methods

© Oxford University Press 2013. All rights reserved.


Method (contd.)
• Return Type:
– can be either void or if a value is returned, it can be either
a primitive type or a class.
– If the method declares a return type, then before it exits it
must have a return statement.
• Method Name:
– The method name must be a valid Java identifier.
• Parameter List:
– contains zero or more type/identifier pairs make up the
parameter list.
– Each parameter in parameter list is separated by a comma.

© Oxford University Press 2013. All rights reserved.


Method (contd.)
• Curly Braces:
– The method body is contained in a set of curly braces
(opening ‘{‘ and closing ‘}’).

© Oxford University Press 2013. All rights reserved.


Method Example
class Circle
{
float pi = 3.14f;
float radius;
void setRadius(float rad)
{
radius = rad;
}
float calculateArea()
{
float area = pi* radius*radius;
return (area);
}
}
© Oxford University Press 2013. All rights reserved.
Method invocation
• Methods cannot run on their own, they need to be
invoked by the objects they are a part of.

• When an object calls a method, it can pass on certain


values to the methods (if methods accept them)

• The methods can also return values from themselves if


they wish to.

• Data that are passed to a method are known as


arguments or parameters.

© Oxford University Press 2013. All rights reserved.


Method Invocation
You must also know about different types of parameters:
• Formal Parameters: the identifier used in a method to stand
for the value that is passed into the method by a caller
E.g. void setData(float rad)
{
radius= rad;
}
• Actual Parameters: The actual value that is passed into the
method by a caller
E.g. obj1.setData(4.5f)

• The number and type of the actual and formal parameters


should be same for a method.
© Oxford University Press 2013. All rights reserved.
Method Invocation
• In Java, all values are passed by value. This is unlike some
other programming languages that allow pointers to
memory addresses to be passed into methods.

•Methods cannot run on their own, they need to be invoked


by the objects they are a part of.

• When an object calls a method, it can pass on certain


values to the methods and the methods can also return
values from themselves if they wish to.

© Oxford University Press 2013. All rights reserved.


Method invocation Example
import java.io.*;
class Circle
{
float pi = 3.14f;
float radius;
void setRadius(float rad)
{
radius = rad;
}
float calculateArea()
{
float area = pi* radius*radius;
return (area);
}

© Oxford University Press 2013. All rights reserved.


Method invocation Example
(contd)
public static void main(String args[])
{
Circle circleobj=new Circle();
circleobj.setRadius(3.0f);
float area= circleobj.calculateArea();
System.out.println("Area of circle:"+ area);
}
}

© Oxford University Press 2013. All rights reserved.


Method Overloading
• In method overloading two methods can have the
same name but different signature i.e. different
number or type of parameters.
• The concept is advantageous where same kind of
activities are to be performed but with different
input parameters

© Oxford University Press 2013. All rights reserved.


Example of Method Overloading
class OverloadDemo
{
void max(float a, float b)
{
System.out.println(“max method with float argument invoked”);
if(a>b)
System.out.println(a+”is greater”);
else
System.out.println(b+”is greater”);
}
void max(double a, double b)
{
System.out.println(“max method with double argument invoked”);
if(a>b)
System.out.println(a+”is greater”);
else
System.out.println(b+”is greater”);
}
© Oxford University Press 2013. All rights reserved.
Example of Method Overloading
(cont)
void max(long a, long b)
{
System.out.println(“max method with long argument invoked”);
if(a>b)
System.out.println(a+”is greater”);
else
System.out.println(b+”is greater”);
}
public static void main(String args[])
{
OverloadDemo o=new OverloadDemo();
o.max(23L,12L);
o.max(2,3);
o.max(54.0,35f);
o.max(43f,35f);
}
}
© Oxford University Press 2013. All rights reserved.
Constructors
• Java has a mechanism, known as constructor, for
automatically initializing the values for an object, as soon as
the object is created.
• Constructors have the same name as the class it resides in and
is syntactically similar to a method.
• It is automatically called immediatey after the object for the
class is created by new operator.
• Contructors have no return type, not even void, as the
implicit return type of a class’ constructor is the class type
itself.
• Types of Constructors: Implicit/Default, Explicit,
Parameterized

© Oxford University Press 2013. All rights reserved.


Explicit Constructor Example
import java.io.*;
class VolumeCalculation
{
double length, breadth, height, volume;
VolumeCalculation()
{
length = 14;
breadth = 12;
height = 10;
}
double volComp()
{
volume = length * breadth * height;
return volume;
}
© Oxford University Press 2013. All rights reserved.
Example (contd.)
public static void main (String args[])
{
VolumeCalculation r1 = new VolumeCalculation();
VolumeCalculation r2 = new VolumeCalculation();
System.out.println("The volume of the room calculated using object
r1 is "+r1.volComp());
System.out.println("The volume of the room calculated using object
r2 is "+r2.volComp());
}
}

© Oxford University Press 2013. All rights reserved.


Parameterized Constructor
Example
import java.io.*;
class VolumeCalculation1
{
double length, breadth, height, volume;
VolumeCalculation1( double l, double b, double h)
{
length = l;
breadth = b;
height = h;
}
double volComp()
{
volume = length * breadth * height;
return volume;
}
© Oxford University Press 2013. All rights reserved.
Example (contd.)
public static void main (String args[ ])
{
VolumeCalculation1 r1 = new VolumeCalculation1(14, 12, 10 );
VolumeCalculation1 r2 = new VolumeCalculation1(16, 15, 11 );
System.out.println("The volume of the room is "+r1.volComp( ));
System.out.println("The volume of the room is "+r2.volComp( ));
}
}

© Oxford University Press 2013. All rights reserved.


Constructor Vs Methods

© Oxford University Press 2013. All rights reserved.


Constructor Overloading
• Constructors for a class have the same name as the
class but they can have different signature i.e.
different types of arguments or different number of
arguments. Such constructors can be termed as
overloaded constructors.
• In the example given on next slide, we have two
different classes, Rectangle and ConstOverloading.
Rectangle class has two constructors, both with same
names but different signatures. Second class
ConstOverloading, has the main( ) method inside it.

© Oxford University Press 2013. All rights reserved.


Constructor Overloading Example
class Rectangle{
int l, b;
Rectangle(){
l = 10;
b = 20;
}
Rectangle(int x, int y){
l = x;
b = y;
}
int area() {
return l*b;
}}

© Oxford University Press 2013. All rights reserved.


Constructor Overloading Example…..
class ConstOverloading {
public static void main(String args[]) {
Rectangle rectangle1=new Rectangle();
System.out.println("The area of a rectangle using first
constructor is: "+rectangle1.area());
Rectangle rectangle2=new Rectangle(4,5);
System.out.println("The area of a rectangle using
second constructor is: "+rectangle2.area();
}}

© Oxford University Press 2013. All rights reserved.


The Output
The area of a rectangle using first constructor is:
200
The area of a rectangle using second constructor
is: 20

© Oxford University Press 2013. All rights reserved.


Cleaning up unused object
• Java allows a programmer to create as many objects as he/she
wants but frees him/her from worrying about destroying
them. The Java runtime environment deletes objects when it
determines that they are no longer required.
• The Java runtime environment has a garbage collector that
periodically frees the memory used by objects that are no
longer needed.
• The garbage collector can be invoked to run at any time by
calling System.gc()
• Finalization: Before an object gets garbage collected, the
garbage collector gives the object an opportunity to clean up
itself through a call to the object's finalize() method. This
process is known as finalization. All occupied resources can
be freed in this method. The finalize() method is member
function of the predefined java.lang.Object class. A class must
override this finalize() method to perform any clean up if
required by©the object.
Oxford University Press 2013. All rights reserved.
Garbage Collector
• Two basic approaches :
– Reference counting and
– tracing.
Reference counting:
• Reference counting maintains a reference count for every
object.
• It is incremented and decremented as and when the
references on objects increase or decrease (leave an
object)
• When reference count for a particular object is 0, the
object can be garbage collected.
© Oxford University Press 2013. All rights reserved.
Garbage Collector (contd.)
Tracing
• Tracing technique traces the entire set of
objects (starting from root) and all objects
having reference on them are marked in some
way.
• Also called as mark and sweep garbage
• The objects that are not marked (not
referenced) are assumed to be garbage and
their memory is reclaimed.

© Oxford University Press 2013. All rights reserved.


Advantages
• Free From worrying about deallocation of
memory.
• helps in ensuring integrity of programs.
• no way by which Java programmers can
knowingly or unknowingly free memory
incorrectly.

© Oxford University Press 2013. All rights reserved.


Disadvantages
• Overhead to keep track of which objects are
being referenced by the executing program
and which are not being referenced
• Overhead is also incurred on finalization and
freeing memory of the unreferenced objects.
• These activities will incur more CPU time than
would have been incurred if the programmers
would have explicitly deallocated memory.

© Oxford University Press 2013. All rights reserved.


static keyword
• Different objects, variables and methods will occupy
different areas of memory when created/called.
Sometimes we would like to have multiple objects, share
variables or methods. The static keyword effectively does
this for us.
• Static keyword can be applied to variables/methods and
blocks of code.
• Java supports three types of variables: Local, Instance and
Class variables
– Local variables are declared inside a method, constructor, or a
block of code
– Instance variable are declared inside a class, but outside a
method

© Oxford University Press 2013. All rights reserved.


static keyword (contd.)
– Class/static variables declaration is preceded with a static
keyword. They are also declared inside a class, but outside
a method. The most important point about static variables
is that there exists only one a single copy of static variables
per class.
– Visibility is similar to instance variables. However, most
static variables are declared public since they must be
available for users of the class.

• The effect of doing this is that when we create multiple


objects of that class, every object shares the static variable
i.e. there is only one copy of the variable declared as static.
We can declare a variables as static as under:
static int var = 0;
© Oxford University Press 2013. All rights reserved.
Example static variable
class Student8{
int rollno;
String name;
static String college ="ITS";

Student8(int r,String n){


rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");

s1.display();
s2.display();
}
}
© Oxford University Press 2013. All rights reserved.
Instance Variables vs. Class Variables
• All instances of the class share the static
variables of the class.
• A class variable can be accessed directly with
the class name, without the need to create an
instance.
• Without the static keyword, it's called
“instance variable”, and each instance of the
class has its own copy of the variable.

© Oxford University Press 2013. All rights reserved.


static methods
• Like static variables, we do not need to create an object
to call our static method. Simply using the class name will
suffice.
• Static methods however can only access static variables
directly.
• Variables that have not been declared static cannot be
accessed by the static method directly, i.e. the reason
why we create an object of the class within the main
(which is static) method to access the instance variables
and call instance methods.
• To make a method static, we simply precede the method
declaration with the static keyword.

© Oxford University Press 2013. All rights reserved.


static methods
static void aMethod(int param1)
{
.....// statement1
.....// statement2
}
• When we declare a method static, we are basically
saying that there should only be one instance of this
method within our program (e.g, as in the main
method)
• Methods can also be declared with the static
keyword.
– static int computeArea(int length, int width) { }

© Oxford University Press 2013. All rights reserved.


Example
import java.io.*;
class Area
{
static int area;
static int computeArea (int width, int height)
{
area = width * height;
return area;
}
}
class callArea
{
public static void main(String args[])
{
System.out.println(Area.computeArea(4,3);
}
}
© Oxford University Press 2013. All rights reserved.
static initialization block
• A block of statements with static keyword
applied to it.
• used for initializing static or class variables.
• in case some logic is used for assigning values
to the variables, static blocks can be used.
• The syntax for static block is as follows:
static{
...
}
© Oxford University Press 2013. All rights reserved.
static initialization block
• The static executes as soon as the class loads
even before the JVM executes the main
method.
• There can be any number of static blocks
within the class and they will be executed in
the order in which they have appeared in the
source code.

© Oxford University Press 2013. All rights reserved.


this keyword
• The keyword “this” is used in an instance method to
refer to the object that contains the method, i.e. the
it refers to the current object.
• Whenever and wherever, a reference to an object of
the current class type is required, ‘this’ can be used.
• It has two other usages:
– Differentiating between instance variables and local
variables
– Constructor chaining

© Oxford University Press 2013. All rights reserved.


this keyword (contd.)
• To differentiate between Instance variables and
local variables
Class Room2
{
double length, breadth, height;
Room2(double length, double breadth, double height)
{this.length = length;
this.breadth = breadth;
this.height = height;
} © Oxford University Press 2013. All rights reserved.
Constructor Chaining
• The constructor chaining is achieve by “this”
statement.
• This statement is used to call constructor of
same class using other constructor.
class MyChaining {
MyChaining(){
System.out.println("In default constructor...");
}
MyChaining(int i){
this();

© Oxford University Press 2013. All rights reserved.


Constructor chaining (cont.)
System.out.println("In single parameter constructor...");
}
MyChaining(int i,int j){
this(j);
System.out.println("In double parameter constructor...");
}

public static void main(String a[]){


MyChaining ch = new MyChaining(10,20);
}
}

© Oxford University Press 2013. All rights reserved.


Command Line Arguments
• Sometimes you will want to pass information into a
program when you run it. This is accomplished by
passing command-line arguments to main( ).
• A command-line argument is the information that
directly follows the program's name on the
command line when it is executed.
• To access the command-line arguments inside a Java
program is quite easy. They are stored as strings in
the String array passed to main( ).

© Oxford University Press 2013. All rights reserved.


Command Line Arguments
• In this case, each of the elements in the array named
args (including the elements at position zero) is a
reference to one of the command line arguments,
each of which is a string object.
• The number of elements in an array can be obtained
from the length property of the array.
• Therefore in the signature of main( ), it is not
necessary in Java to pass a parameter specifying the
number of arguments.

© Oxford University Press 2013. All rights reserved.


Example
Example
public class CommandLine{
public static void main(String args[]){
for(int i=0; i<args.length; i++){
System.out.println("args["+ i +"]: "+args[i]);}}}

• After compiling the program, when it is executed, you can


pass the command line arguments as follows,
• java CommandLine this is a command line 200-100

© Oxford University Press 2013. All rights reserved.


The output
• args[0]:this
• args[1]:is
• args[2]: a
• args[3]: command
• args[4]: line
• args[5]:200
• args[6]:-100

© Oxford University Press 2013. All rights reserved.


Array
• There are situations where we might wish to store a
group of similar type of values in a variable.
• Array is a memory space allocated, which can store
multiple values of same data type, in contiguous
locations.
• This memory space, which can be perceived to have
many logical contiguous locations, can be accessed
with a common name.

© Oxford University Press 2013. All rights reserved.


Summary
• A class provides a sort of template or blueprint for an
object.
• An object is a software bundle which encapsulates
variables and methods, operating on those variables.
• A Java object is defined as an instance of a class.
• A class can have many instances of objects, each
having its own copy of variable and methods. The
variables declared inside a class (but outside a
method) are termed as instance variable. Attributes
of a class are defined by instance variables, while its
behavior is defined by methods.

© Oxford University Press 2013. All rights reserved.


Summary (contd.)
• These methods, declared as part of one object can be invoked
or called from another object. The method or variable
belonging to a particular can be accessed by specifying the
name of the object to which they belong to.
• A special type of variable, whose value remains the same
through out all the objects of a class, is known as class or
static variable. Likewise a method can also be declared as
static, which exist within the one location in memory no
matter how many times it is called from multiple objects. Both
static variable and static method can be called directly from
anywhere inside a class, without specifying any object name.
• In java the objects are automatically freed after their use. The
garbage collector periodically frees the memory used by
objects that are no longer needed

© Oxford University Press 2013. All rights reserved.


Summary (contd.)
• Method Overloading and overriding are two ways of
implementing polymorphism in java.
• Command Line Arguments is a way fo passing input
to Java programs.
• Arrays are used to hold to hold data of similar type.
There can be of 1-dimensional or multidimensional
arrays.

© Oxford University Press 2013. All rights reserved.

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