Unit 1 Classes
Unit 1 Classes
1
Contents
• Introduction to classes and objects in Java.
• Understand how some of the OO concepts learnt so far are supported in
Java.
• Understand important features in Java classes.
2
Introduction
• Java is a true Object Oriented language and therefore
the underlying structure of all Java programs is
classes.
• Anything we wish to represent in Java must be
encapsulated in a class that defines the “state” and
“behavior” of the basic program components known
as objects.
• Classes create objects and objects use methods to
communicate between them.
3
Classes
• A class is a user defined abstract datatype.
class Box { mybox
double width; Widwidth=
10
double length; ,length=15,
Depth=12
double depth;
} to create the object syntax
Box mybox=new Box( );
4
Program to demonstrate working of a
class
5
class Box {
double width; //declared variables
double length;
double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[ ]) {
Box mybox = new Box(); //an object mybox of the class box is created,new is
the keyword thru which it is created.
Box mybox1=new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.length = 20;
mybox.depth = 15;
mybox1.width = 20;
mybox1.length =30;
mybox1.depth = 45;
7
Adding Methods to Class Circle
class Box {
double width;
double length;
double depth;
8
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box(); W=10,l=20,
3,6,9
d=15
// assign values to mybox1's instance variables
mybox1.width = 10; myobj1 myobj2
mybox1.length = 20;
mybox1.depth = 15;