Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
7 views17 pages

7 Classesandobjects

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

7 Classesandobjects

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

Introducing Classes

Simple Pgm-1
class Box
{
double width;
double height;
double depth;

public static void main(String args[])


{

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


mybox.width = 100;
width=100 //error b’coz main function is static
System.out.println(mybox.width);

}
}
class BoxDemo2

class Box { {
public static void main(String args[])
double width, {
Box mybox1 = new Box();
height, depth; Box mybox2 = new Box();

} double vol;

// assign values to mybox1's instance variables


mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;

/* assign different values to mybox2's instance variables */


mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;

// compute volume of first box


vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);

// compute volume of second box


output
vol = mybox2.width * mybox2.height * mybox2.depth;
Volume is 3000.0
System.out.println("Volume is " + vol);
Volume is 162.0 }
}
• Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
Assigning Object Reference Variables
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.
class BoxDemo3 {
Introducing Methods public static void main(String args[])
{
// This program includes a Box mybox1 = new Box();
method inside the box class. Box mybox2 = new Box();
class Box {
// assign values to mybox1's instance variables
double width;
mybox1.width = 10;
double height; mybox1.height = 20;
double depth; mybox1.depth = 15;

// display volume of a box /* assign different values to mybox2's instance


variables */
void volume() { mybox2.width = 3;
System.out.print("Volume is "); mybox2.height = 6;
System.out.println(width * height * mybox2.depth = 9;
depth);
// display volume of first box
}
mybox1.volume();
}
output // display volume of second box
mybox2.volume();
Volume is 3000.0 }
Volume is 162.0 }
Constructors

• initialize all of the variables in a class each time an instance is


created.
• they have no return type, not even void.
• because the implicit return type of a class’ constructor is the
class type itself.
• When constructor is not defined in a class the compiler
provides a default constructor which initializes all the instance
variables to their default values.
• When we provide at least one constructor to our class, then the
compiler no more provides a constructor.

class Student
{
public Student ( int m )
{ }
}
class StudentTest
{
public static void main ( String arg[] )
{
Student s=new Student(); // Incorrect
}
}
error: constructor in class cannot
be applied to given types;
• if we do not initialize any variables in the constructors then they too are set to their
default values.
• This is not the case with local variables (those defined in methods).
class Student
{ int m; //constructor initialize m, value is 0
public void function()
{ int x;
System.out.println(m);
/* A compilation error would be generated saying that x was not initialized*/
System.out.println(x);
}
}
class StudentTest
{ public static void main ( String args[] )
{ Student s=new Student();
s.function();
}
}
E:\>javac StudentTest.java
StudentTest.java:7: error: variable x might not have been initialized
System.out.println(x);
^
1 error
The this Keyword

• this can be used inside any method to refer to the current object.
class Box
{ double width;
double height;
double depth;
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
}
• Instance Variable Hiding
local variable has the same name as an instance variable, the local
variable hides the instance variable.
• Garbage Collection
– 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 no longer needed, and the memory
occupied by the object can be reclaimed.
– Garbage collector(a part of JVM)
– System.gc() :to invoke the garbage collector explicitly
– But this not guarantee that jvm will perform garbage
collection
The finalize( ) Method
• Sometimes an object will need to perform some action
when it is destroyed.
• For that Java provides a mechanism called finalization.
• finalize()-The Java run time calls that method
whenever recycle an object
• The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
finalize( ) is only called just prior to garbage collection. It
is not called when an object goes out-of-scope,
Stack program class TestStack {
class Stack {
int stck[] = new int[10]; public static void main(String args[]) {
int tos; Stack mystack1 = new Stack();
// Initialize top-of-stack Stack mystack2 = new Stack();
Stack() {
tos = -1;
// push some numbers onto the stack
}
// Push an item onto the stack for(int i=0; i<10; i++)
void push(int item) { mystack1.push(i);
if(tos==9) for(int i=10; i<20; i++)
System.out.println("Stack is full."); mystack2.push(i);
else
stck[++tos] = item;
} // pop those numbers off the stack
// Pop an item from the stack System.out.println("Stack in mystack1:"); for(int
int pop() { i=0; i<10; i++)
if(tos < 0) { System.out.println(mystack1.pop());
System.out.println("Stack underflow.");
return 0;
System.out.println("Stack in mystack2:");
}
for(int i=0; i<10; i++)
else
return stck[tos--]; System.out.println(mystack2.pop());
} }
} }
Access Specifiers
• Access specifiers are used to control the
visibility of members like classes, variables and
methods.
• Packages: group of related classes.
– Packages help in organizing classes.
– Every class is a part of a single package.
– When we do not explicitly specify to which
package a class belongs, it is placed in the default
package.
– Before use a class from a package, we need to
import either the entire package or that particular
class by using the import statement
• Four Access specifier
– public
– Private
– Protected
– Default
• that all four levels may be applied to all
elements except classes.
(but if class is an inner class four levels are
allowed)
Accessibility of entities

private default protected public


Same class yes yes yes yes
Same package no yes yes yes
not subclass
Same package no yes yes yes
subclass
Other package no no no yes
not subclass
Other package no no yes yes
subclass
Array of Objects

class Student {
int marks;
}
• Student[] studentArray = new Student[7];
– It creates the array which can hold references to seven Student objects. It
doesn't create the Student objects themselves.

• studentArray[0].marks = 100;
– This throws a NullPointerException during runtime which indicates that
studentArray[0] isn't yet pointing to a Student object.

• studentArray[0] = new Student();


– studentArray[0].marks = 100;// now it will work

• for ( int i=0; i<studentArray.length; i++)


{
studentArray[i]=new Student();
}

You might also like