[go: up one dir, main page]

0% found this document useful (0 votes)
19 views56 pages

Classes & Objects

Uploaded by

moh24amme
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)
19 views56 pages

Classes & Objects

Uploaded by

moh24amme
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/ 56

Classes & objects

Syllabi
• Introducing Classes: Class Fundamentals,
Declaring Objects, Assuming Object reference
Variables, Introducing Methods, Constructors, The
this Keyword, Garbage Collection, The Finalize()
method, A Stack class.
Class Fundamentals
• A class, defines a new data type.
• Once defined, this new type can be used to
create objects of that type.
• Thus, a class is a template for an object, and an
object is an instance of a class.
• Because an object is an instance of a class, the
two words object and instance used
interchangeably.
The General Form of a Class
• A class is declared by use of the class keyword.
• Classes may contain only code or only data, most real-world classes contain
both.
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
The General Form of a Class
• The data, or variables, defined within a class are
called instance variables.
• The code is contained within methods.
• Collectively, the methods and variables defined
within a class are called members of the class.
• Variables defined within a class are called
instance variables because each instance of the
class (that is, each object of the class) contains its
own copy of these variables. Thus, the data for
one object is separate and unique from the data
for another.
A Simple Class

• a class declaration only creates a template;


class Box {
double width;
double height;
double depth;
}
Box mybox = new Box(); // create a Box object called mybox
mybox will be an instance of Box. Thus, it will have “physical” reality. To access class variables, use the dot (.)
operator.
The dot operator links the name of the object with the name of an instance
variable.
mybox.width = 100;
/* A program that uses the Box class. Call this file BoxDemo.java */
class Box {
double width;
double height;
double depth;
}

class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;

vol = mybox.width * mybox.height * mybox.depth;


System.out.println("Volume is " + vol);
}
}
Declaring Objects
• Obtaining objects of a class is a two-step process.
• First, you must declare a variable of the class type. This variable
does not define an object. Instead, it is simply a variable that can
refer to an object.
Box mybox; // declare reference to object
• Second, you must acquire an actual, physical copy of the object
and assign it to that variable. You can do this using the new
operator.
mybox = new Box(); // allocate a Box object
• The new operator dynamically allocates (that is, allocates at run time)
memory for an object and returns a reference to it. This reference is,
more or less, the address in memory of the object allocated by new.
• This reference is then stored in the variable.
Assigning Object Reference Variables
• Object reference variables act differently when an assignment takes place.
Box b1 = new Box();
Box b2 = b1;

Box b1 = new Box();


Box b2 = b1;
// ...
b1 = null;
Here, b1 has been set to null, but b2 still points to the original object.
When you assign one object reference variable to another object reference variable, you are
not creating a copy of the object, you are only making a copy of the reference.
Introducing Methods
type name(parameter-list) {
// body of method
return value;
}
• 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.
• value is the value returned.
Adding method
• Method With parameters
• Method Without Parameters
• Method Return a value
• The type of data returned by a method must be
compatible with the return type specified by the
method.
• The variable receiving the value returned by a
method must also be compatible with the return
type specified for the method.
Example
void volume()
{
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
Returning a Value

double volume() {
return width * height * depth;
}
Adding a Method That Takes Parameters

int square() int square(int i)


{ {
return 10 * 10; return i * i;
} }
Constructors
• Automatic initialization of an object is performed
through the use of a constructor.
• A constructor initializes an object immediately upon
creation.
• It has the same name as the class in which it resides
and is syntactically similar to a method.
• Once defined, the constructor is automatically called
immediately after the object is created, before the
new operator completes.
• Constructors have no return type, not even void. This
is because the implicit return type of a class
constructor is the class type itself.
• The constructor’s job to initialize the internal state of
an object.
Constructors
• Constructors are
1. Default Constructors
Box mybox1 = new Box();
The default constructor automatically initializes all
instance variables to zero.
3. Parameterized Constructors
Box mybox1 = new Box(10, 20, 15);
4. Copy Constructors
class Box { 1. Default Constructors
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
} class BoxDemo6 {
// compute and return volume public static void main(String args[]) {
double volume() { // declare, allocate, and initialize Box objects
return width * height * depth; Box mybox1 = new Box();
} Box mybox2 = new Box();
} double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
OUTPUT: // get volume of second box
Volume is 3000.0 vol = mybox2.volume();
Volume is 162.0 System.out.println("Volume is " + vol);
}
}
class Box { Parameterized Constructors
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume class BoxDemo7 {
double volume() { public static void main(String args[]) {
return width * height * depth; // declare, allocate, and initialize Box objects
} Box mybox1 = new Box(10, 20, 15);
} Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
OUTPUT: // get volume of second box
Constructing Box vol = mybox2.volume();
Constructing Box System.out.println("Volume is " + vol);
Volume is 1000.0 }
Volume is 1000.0 }
Stack Program Structure
Class stack{ void push(int ele)
Int top; {
Int a[]; if(top==max-1)
stack(int n) //using constructor {
{
max=n; System.out.println(“Stack OVER FLOW - Elements
a=new int[max]; in the array are :”+max);
top=-1;
} }
else
{
a[++top]=ele;
}
}

}
void pop()
{
if(top==-1)
{
System.out.println(“Stack Underflow”);
}
else
{
System.out.println(“Poped Element is :” +a[top--]);
}
}
The this Keyword
• Sometimes a method will need to refer to the
object that invoked it.
• To allow this, Java defines the this keyword.
• this can be used inside any method to refer to the
current object. That is, this is always a reference to
the object on which the method was invoked.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
• Usage of java this keyword
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the
method.
Instance Variable Hiding
• It is illegal in Java to declare two local variables with the same name
inside the same or enclosing scopes.
• Local variables, including formal parameters to methods, which overlap
with the names of the class’ instance variables.
• However, when a local variable has the same name as an instance
variable, the local variable hides the instance variable.
• this, resolve any name space collisions that might occur between
instance variables and local variables.
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
Overloading constructors
public class Rectangle {
int x, y;
int width, height;

Rectangle()
{
this(0, 0, 1, 1);
}
Rectangle(int width, int height)
{
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public class student
{
private int rollNum;
student()
{
rollNum =100;
}
student(int rnum)
{
this();
rollNum = rollNum+ rnum;
}
public int getRollNum() {
return rollNum;
}
public void setRollNum(int rollNum) {
this.rollNum = rollNum;
}
}
Garbage Collection

• Since objects are dynamically allocated by using the new operator, 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 automatically.
The technique that accomplishes this is called garbage collection.
• When no references to an object exist, that object is assumed to be
unreachable, and the memory occupied by the object can be
reclaimed.
• Advantage of Garbage Collection
• o It makes java memory efficient because garbage collector removes the unreferenced objects from heap
memory.
• o It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.
Ways to collect Garbage
• By anonymous object: new Student();
• By nulling reference:
• Student s = new Student();
• s = null;
• By assigning a reference to another object:
• Student s1 = new Student();
• Student s2 = new Student();
• s1 = s2;
• The garbage collector in Java can be called explicitly
using the following method:

• System.gc();

• System.gc() is a method in Java that invokes garbage


collector which will destroy the unreferenced
objects. System.gc() calls finalize() method only once
for each object.
• finalize() method in Java is a method of the Object class that is used
to perform cleanup activity before destroying any object.
• It is called by Garbage collector before destroying the objects from
memory.
• finalize() method is called by default for every object before
its deletion.
• Java Virtual Machine(JVM) permits invoking of finalize() method only
once per object.
Overloading Methods
• In Java, it is possible to define two or more methods within the same
class that share the same name, as long as their parameter
declarations are different.
• Method overloading is also known as Static Polymorphism.
• Argument lists could differ in –
1. Number of parameters.
2. Data type of parameters.
3. Sequence of Data type of parameters
Advantage of method overloading
• Method overloading increases the readability of the program.
• It adds cleanliness to the code written.
• It can be used on constructors also so that we can create different
objects by passing different data.
• It gives the programmers the flexibility of calling different methods
with similar names.
• Overloaded methods can have different return types.
Static
• to define the class members that will be used independent of any
object of that class.
• initialized for the first time when the class is loaded.

• main( ) is declared as static because it must be called before any


objects exist.[i.e., without instantiating the class]
Static Methods
• Methods declared as static have several restrictions:

• They can only directly call other static methods.


• They can only directly access static data.
• They cannot refer to this or super in any way.
Static Blocks:
• Static blocks are also called Static initialization blocks .
• A static initialization block is a normal block of code enclosed in
braces, { }, and preceded by the static keyword.

static {
//code
}
class UseStatic
{
static int a = 3;
static int b;
static void display (int x)
{
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static
{
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[])
{
display (42);
}
}
Calling static outside the class
• With class name
Recursion
• recursion is the attribute that allows a method to call itself.
Access Control
• The access modifiers in java specifies accessibility (scope) of a data
member, method, constructor or class.
• There are 4 types of java access modifiers:
1. private
2. default
3. protected
4. public
Public
private:
protected:
default
Object as Parameters
class Add public class classExAdd
{ {
int a; public static void main(String
int b; arg[])
{
Add(int x,int y)// parametrized constructor Add A=new Add(5,8);
{ A.sum(A);
a=x; }
b=y; }
}
void sum(Add A1) {
int sum1=A1.a+A1.b;
System.out.println("Sum of a and b
:"+sum1);
}
}
• Write a java program to create 2 objects of complex numbers and
pass these objects as parameters to the methods. Perform addition of
2 complex numbers and return the sum as an object.
final

You might also like