Object Oriented
Programming-1
What is Object Oriented Programming?
• Object-oriented programming (OOP) involves programming using
classes and objects
• OOP using two mechanisms:
• Classes
• Objects
• How OOP is different from Procedural Programming?
What is Class?
• Class can be defined in the following ways:
• A class is a template for an object
• A class is creating a user defined type
• A class is a blueprint
• A class is a template or blueprint that defines what an object’s data
fields and methods will be
• Class contain:(class members)
• Properties
• Methods
Properties:
• Properties are the attributes of the objects of a class. These are used
to differentiate one class of objects from another class.
• For example a class that represents a pen could be created with the
following attributes:
• Color of the pen
• Size of the pen
• Type of the pen
Methods:
• Methods represent behavior of the class and consist of codes that
operate on data.
• A method is a set of code which is referred to by name and can be
called (invoked) at any point in a program simply by utilizing the
method's name. Think of a method as a subprogram that acts on
data and often returns a value.
• How to define a method, lets understand with the help of simple
example.
Mpl 9 oop
How to define a Class in Java?
General Syntax:
class classname
{
type instance-variable1;
type instance-variable2;
type methodname1(parameter-list)
{
statements;
}
}
A Java class uses variables to
define data fields and methods
to define actions.
What is Object?
• Object is an instance of the class, you can create many instances of a
class.
A Simple Class
class Box {
double width;
double height;
double depth;
}
9
Creating Objects
There are two steps to create an object:
Method 1:
1st create an object reference variable:
Box mybox;
2nd physically create an object and assign it to the reference variable
mybox = new Box( );
Method 2:
Box mybox = new Box( );
• After executing this statement, an object of class Box will be created with
the name mybox.
10
11
Object Oriented Program Features
• Encapsulation:
• Combining data and methods into a single unit called class and the process is
known as Encapsulation.
• Data encapsulation is important feature of a class that provide security.
• The insulation of the data from direct access by the program is called data
hiding or information hiding.
• Inheritance:
• The process by which object of one class acquire the properties or features of
objects of another class.
• The concept of inheritance provide the idea of reusability means we can add
additional features to an existing class without Modifying it.
• This is possible by deriving a new class from the existing one. The new class
will have the combined features of both the classes.
• Polymorphism
• A Greek term means ability to take more than one form.
• Function name will be the same, but parameter list will be different
• Java provides two ways to implement polymorphism.
• Static Polymorphism (compile time polymorphism/ Method overloading)
• Dynamic Polymorphism (run time polymorphism/ Method Overriding)
Access Modifiers
• A Java access modifier specifies which classes can access a given class
and its fields, constructors and methods.
• Classes, fields, constructors and methods can have one of four
different Java access modifiers:
• private
• default (package)
• protected
• public
• private Access Modifier
• If a method or variable is marked as private then only code inside
the same class can access the variable, or call the method.
• Code inside subclasses cannot access the variable or method, nor can
code from any external class.
• Private access modifier is not allowed for classes
• default (package) Access Modifier
• The default Java access modifier is declared by not writing any access
modifier at all.
• The default access modifier means that code inside the class itself as
well as code inside classes in the same package as this class, can
access the class, field, constructor or method which the default access
modifier is assigned to.
• protected Access Modifier
• The protected access modifier provides the same access as the default access
modifier, with the addition that subclasses can access protected methods and
member variables (fields) of the superclass.
• This is true even if the subclass is not located in the same package as the
superclass.
• public Access Modifier
• The Java access modifier public means that all code can access the class, field,
constructor or method, regardless of where the accessing code is located.
• The accessing code can be in a different class and different package.
Access Protection
Program 1
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;
18
Program1…
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
19
Example 2
class Box {
double width;
double height;
double depth;
}
class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
20
Example 2…
double vol;
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
21
Example 2…
// compute volume of first box
vol = mybox1.width * mybox1.height *mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
}
22
Output of Example 2…
The output produced by this program is shown here:
Volume is 3000.0
Volume is 162.0
23
Adding A Method to The Box Class
Since the volume of a box is dependent upon the size of the box, it
makes sense to have the Box class compute it. To do this, we must add a
method to Box.
24
Adding A Method to The Box Class
class Box {
double width;
double height;
double depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
25
Continue…
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
mybox1.volume();
mybox2.volume();
}
}
26
Returning A Value
• While the implementation of volume( ) does move the computation of a box’s
volume inside the Box class where it belongs, it is not the best way to do it.
• For example, what if another part of your program wanted to know the
volume of a box, but not display its value? A better way to implement volume(
) is to have it compute the volume of the box and return the result to the
caller.
• The following example, does just that.
27
Returning Value Program…
// Now, volume() returns the volume of a box.
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo4 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
28
Returning Value Program…
// 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;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
} 29
Method That Takes Parameter
• Parameters allow a method to be generalized. That is, a parameterized
method can operate on a variety of data and be used in a number of slightly
different situations. To show this point, let’s use a very simple example.
Here is a method that returns the square of the number 10:
int square()
{
return 10 * 10;
}
30
Method That Takes Parameter
• While the previous method does, indeed, return the value of 10 squared, its
use is very limited.
• However, if we modify the method so that it takes a parameter, as shown next,
then we can make square( ) much more useful.
int square(int i)
{
return i * i;
}
31
Box Program
• Thus, a better approach to setting the dimensions of a box is to create a
method that takes the dimension of a box in its parameters and sets each
instance variable appropriately.
• This concept is implemented by the following program:
32
Box Program…
// This program uses a parameterized method.
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
33
Box Program…
// sets dimensions of box
void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
}
34
Box Program…
class BoxDemo5 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// initialize each box
mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
35
Box Program…
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
36
Constructor
• A constructor is a method that executes automatically whenever an object
is created.
• It has the same name as the class in which it is created.
• Constructors have no return type, not even void. This is because the
implicit return type of a class’ constructor is the class type itself.
37
Example
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume() {
return width * height * depth;
}
} 38
Example…
class BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
39
Parameterized Constructors
• While the Box( ) constructor in the previous example does
initialize a Box object, but it is not very useful because all boxes
have the same dimensions.
• Actually we need a way to construct Box objects of various
dimensions. The easy solution is to add parameters to the
constructor.
40
Example Program
class Box {
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
double volume() {
return width * height * depth;
}
} 41
Example Program…
class BoxDemo7 {
public static void main(String args[]) {
// 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);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
} 42
Output
The output from this program is shown here:
Volume is 3000.0
Volume is 162.0
43

More Related Content

PPT
gdfgdfg
PDF
Object oriented programming
PPT
06 inheritance
PPS
Introduction to class in java
PDF
C# (This keyword, Properties, Inheritance, Base Keyword)
PDF
PPT
Java oops PPT
PDF
Class notes(week 6) on inheritance and multiple inheritance
gdfgdfg
Object oriented programming
06 inheritance
Introduction to class in java
C# (This keyword, Properties, Inheritance, Base Keyword)
Java oops PPT
Class notes(week 6) on inheritance and multiple inheritance

What's hot (20)

DOCX
Introduction to object oriented programming concepts
PPT
Object and Classes in Java
PDF
Java OOP Programming language (Part 5) - Inheritance
DOCX
JAVA Notes - All major concepts covered with examples
PDF
Java Day-7
PPTX
OOPS Basics With Example
DOCX
Unit3 java
PPTX
Unit3 inheritance
PPTX
Classes, objects in JAVA
PPT
6 Inheritance
PPTX
Unit3 part2-inheritance
PPTX
14 Defining Classes
DOCX
Java sessionnotes
PDF
Python unit 3 m.sc cs
PDF
Java Day-3
PPTX
OBJECT ORIENTED PROGRAMING IN C++
PDF
Object Oriented Programming in PHP
PDF
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
PPTX
Unit ii
Introduction to object oriented programming concepts
Object and Classes in Java
Java OOP Programming language (Part 5) - Inheritance
JAVA Notes - All major concepts covered with examples
Java Day-7
OOPS Basics With Example
Unit3 java
Unit3 inheritance
Classes, objects in JAVA
6 Inheritance
Unit3 part2-inheritance
14 Defining Classes
Java sessionnotes
Python unit 3 m.sc cs
Java Day-3
OBJECT ORIENTED PROGRAMING IN C++
Object Oriented Programming in PHP
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Unit ii
Ad

Viewers also liked (16)

PDF
A la-ética
PDF
Khudozhnya kultura-10-klas-klimova
PDF
Geometriya 11-klas-bevz-2011
PDF
Informatika 10-klas-morze-2010
PDF
Istoriya ukrajini-10-klas-kulchickijj-lebedehva
PDF
wilder_teaching_statement
PDF
Українська література 6 клас Авраменко 2014 от Freegdz.com
PPTX
Location-based Learning
PPTX
Preprocessor
PDF
Permendikbud70 2013 kd-strukturkurikulum-smk-mak
DOCX
Target audiece profile
PPTX
Media Evaluation Question 5
PPT
Java non access modifiers
PPTX
Lesiones pulmonares cavitadas
PPTX
A la-ética
Khudozhnya kultura-10-klas-klimova
Geometriya 11-klas-bevz-2011
Informatika 10-klas-morze-2010
Istoriya ukrajini-10-klas-kulchickijj-lebedehva
wilder_teaching_statement
Українська література 6 клас Авраменко 2014 от Freegdz.com
Location-based Learning
Preprocessor
Permendikbud70 2013 kd-strukturkurikulum-smk-mak
Target audiece profile
Media Evaluation Question 5
Java non access modifiers
Lesiones pulmonares cavitadas
Ad

Similar to Mpl 9 oop (20)

PPTX
JAVA Module 2jdhgsjdsjdjsddsjjssdjdsjhsdjh.pptx
PPT
5.CLASSES.ppt(MB)2022.ppt .
PPTX
JAVA Module 2____________________--.pptx
PPTX
JAVA Module 2 ppt on classes and objects and along with examples
PPTX
Class object method constructors in java
PDF
Session 3 Constructors, Types, Overloading, Static MethodsNotes.pdf
PPTX
unit 2 java.pptx
PPT
6.INHERITANCE.ppt(MB).ppt .
PPTX
Classes, Objects and Method - Object Oriented Programming with Java
PPTX
Chapter ii(oop)
PPTX
Classes, Inheritance ,Packages & Interfaces.pptx
PPT
7_-_Inheritance
PPTX
Class and object
PPT
gdfgdfg
PPT
Super keyword.23
PPT
PPTX
UNIT_-II_2021R.pptx
PPTX
OOP C++
DOCX
java classes
PDF
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
JAVA Module 2jdhgsjdsjdjsddsjjssdjdsjhsdjh.pptx
5.CLASSES.ppt(MB)2022.ppt .
JAVA Module 2____________________--.pptx
JAVA Module 2 ppt on classes and objects and along with examples
Class object method constructors in java
Session 3 Constructors, Types, Overloading, Static MethodsNotes.pdf
unit 2 java.pptx
6.INHERITANCE.ppt(MB).ppt .
Classes, Objects and Method - Object Oriented Programming with Java
Chapter ii(oop)
Classes, Inheritance ,Packages & Interfaces.pptx
7_-_Inheritance
Class and object
gdfgdfg
Super keyword.23
UNIT_-II_2021R.pptx
OOP C++
java classes
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf

Recently uploaded (20)

PPTX
一比一原版(Hanze UAS毕业证)荷兰格罗宁根应用科学大学毕业证如何办理
PPTX
Prezentacja HY 2025 EN prezentacjaaa.pptx
PDF
20250807financial-results-presentation-English.pdf
PDF
AFC Asia Frontier Fund (non-US) Factsheet July 2025
PDF
AFC Vietnam Fund Factsheet July 2025 english
PDF
Collective Mining | Corporate Presentation - August 2025
PDF
AFC Iraq Fund Presentation - August 2025
PDF
Searchends Inclusion Impack Investors Deck
DOCX
MLS 112 Human Anatomy and Physiology with Pathophysiology (LECTURE).docx
PPTX
伦敦大学亚非学院硕士毕业证SOAS成绩单伦敦大学亚非学院Offer学历认证
PDF
Collective Mining | Corporate Presentation - August 2025
PDF
AFC Vietnam Fund Presentation - August 2025
PPTX
伦敦政治经济学院假毕业证LSE成绩单伦敦政治经济学院在读证明信学历认证
PDF
Raheja CIRP Order 210825 - All Projects.pdf
PDF
AFC Iraq Fund (non-US) Factsheet July 2025
PDF
AFC Asia Frontier Fund Presentation August 2025
PPTX
原版一样(SMC毕业证书)美国圣莫尼卡学院毕业证100%复刻研究生学历信息学历认证
PDF
AFC Uzbekistan Fund (non-US) Factsheet July 2025
PDF
AFC Uzbekistan Fund Presentation August 2025
PPTX
223Presentation2.pptxGUFYFDYVHGF6FVUF6UY
一比一原版(Hanze UAS毕业证)荷兰格罗宁根应用科学大学毕业证如何办理
Prezentacja HY 2025 EN prezentacjaaa.pptx
20250807financial-results-presentation-English.pdf
AFC Asia Frontier Fund (non-US) Factsheet July 2025
AFC Vietnam Fund Factsheet July 2025 english
Collective Mining | Corporate Presentation - August 2025
AFC Iraq Fund Presentation - August 2025
Searchends Inclusion Impack Investors Deck
MLS 112 Human Anatomy and Physiology with Pathophysiology (LECTURE).docx
伦敦大学亚非学院硕士毕业证SOAS成绩单伦敦大学亚非学院Offer学历认证
Collective Mining | Corporate Presentation - August 2025
AFC Vietnam Fund Presentation - August 2025
伦敦政治经济学院假毕业证LSE成绩单伦敦政治经济学院在读证明信学历认证
Raheja CIRP Order 210825 - All Projects.pdf
AFC Iraq Fund (non-US) Factsheet July 2025
AFC Asia Frontier Fund Presentation August 2025
原版一样(SMC毕业证书)美国圣莫尼卡学院毕业证100%复刻研究生学历信息学历认证
AFC Uzbekistan Fund (non-US) Factsheet July 2025
AFC Uzbekistan Fund Presentation August 2025
223Presentation2.pptxGUFYFDYVHGF6FVUF6UY

Mpl 9 oop

  • 2. What is Object Oriented Programming? • Object-oriented programming (OOP) involves programming using classes and objects • OOP using two mechanisms: • Classes • Objects • How OOP is different from Procedural Programming?
  • 3. What is Class? • Class can be defined in the following ways: • A class is a template for an object • A class is creating a user defined type • A class is a blueprint • A class is a template or blueprint that defines what an object’s data fields and methods will be • Class contain:(class members) • Properties • Methods
  • 4. Properties: • Properties are the attributes of the objects of a class. These are used to differentiate one class of objects from another class. • For example a class that represents a pen could be created with the following attributes: • Color of the pen • Size of the pen • Type of the pen
  • 5. Methods: • Methods represent behavior of the class and consist of codes that operate on data. • A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name. Think of a method as a subprogram that acts on data and often returns a value. • How to define a method, lets understand with the help of simple example.
  • 7. How to define a Class in Java? General Syntax: class classname { type instance-variable1; type instance-variable2; type methodname1(parameter-list) { statements; } } A Java class uses variables to define data fields and methods to define actions.
  • 8. What is Object? • Object is an instance of the class, you can create many instances of a class.
  • 9. A Simple Class class Box { double width; double height; double depth; } 9
  • 10. Creating Objects There are two steps to create an object: Method 1: 1st create an object reference variable: Box mybox; 2nd physically create an object and assign it to the reference variable mybox = new Box( ); Method 2: Box mybox = new Box( ); • After executing this statement, an object of class Box will be created with the name mybox. 10
  • 11. 11
  • 12. Object Oriented Program Features • Encapsulation: • Combining data and methods into a single unit called class and the process is known as Encapsulation. • Data encapsulation is important feature of a class that provide security. • The insulation of the data from direct access by the program is called data hiding or information hiding.
  • 13. • Inheritance: • The process by which object of one class acquire the properties or features of objects of another class. • The concept of inheritance provide the idea of reusability means we can add additional features to an existing class without Modifying it. • This is possible by deriving a new class from the existing one. The new class will have the combined features of both the classes. • Polymorphism • A Greek term means ability to take more than one form. • Function name will be the same, but parameter list will be different • Java provides two ways to implement polymorphism. • Static Polymorphism (compile time polymorphism/ Method overloading) • Dynamic Polymorphism (run time polymorphism/ Method Overriding)
  • 14. Access Modifiers • A Java access modifier specifies which classes can access a given class and its fields, constructors and methods. • Classes, fields, constructors and methods can have one of four different Java access modifiers: • private • default (package) • protected • public
  • 15. • private Access Modifier • If a method or variable is marked as private then only code inside the same class can access the variable, or call the method. • Code inside subclasses cannot access the variable or method, nor can code from any external class. • Private access modifier is not allowed for classes • default (package) Access Modifier • The default Java access modifier is declared by not writing any access modifier at all. • The default access modifier means that code inside the class itself as well as code inside classes in the same package as this class, can access the class, field, constructor or method which the default access modifier is assigned to.
  • 16. • protected Access Modifier • The protected access modifier provides the same access as the default access modifier, with the addition that subclasses can access protected methods and member variables (fields) of the superclass. • This is true even if the subclass is not located in the same package as the superclass. • public Access Modifier • The Java access modifier public means that all code can access the class, field, constructor or method, regardless of where the accessing code is located. • The accessing code can be in a different class and different package.
  • 18. Program 1 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; 18
  • 19. Program1… mybox.height = 20; mybox.depth = 15; vol = mybox.width * mybox.height * mybox.depth; System.out.println("Volume is " + vol); } } 19
  • 20. Example 2 class Box { double width; double height; double depth; } class BoxDemo2 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); 20
  • 21. Example 2… double vol; mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; 21
  • 22. Example 2… // compute volume of first box vol = mybox1.width * mybox1.height *mybox1.depth; System.out.println("Volume is " + vol); // compute volume of second box vol = mybox2.width * mybox2.height * mybox2.depth; System.out.println("Volume is " + vol); } } 22
  • 23. Output of Example 2… The output produced by this program is shown here: Volume is 3000.0 Volume is 162.0 23
  • 24. Adding A Method to The Box Class Since the volume of a box is dependent upon the size of the box, it makes sense to have the Box class compute it. To do this, we must add a method to Box. 24
  • 25. Adding A Method to The Box Class class Box { double width; double height; double depth; void volume() { System.out.print("Volume is "); System.out.println(width * height * depth); } } class BoxDemo3 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); 25
  • 26. Continue… mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; mybox1.volume(); mybox2.volume(); } } 26
  • 27. Returning A Value • While the implementation of volume( ) does move the computation of a box’s volume inside the Box class where it belongs, it is not the best way to do it. • For example, what if another part of your program wanted to know the volume of a box, but not display its value? A better way to implement volume( ) is to have it compute the volume of the box and return the result to the caller. • The following example, does just that. 27
  • 28. Returning Value Program… // Now, volume() returns the volume of a box. class Box { double width; double height; double depth; // compute and return volume double volume() { return width * height * depth; } } class BoxDemo4 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; 28
  • 29. Returning Value Program… // 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; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } } 29
  • 30. Method That Takes Parameter • Parameters allow a method to be generalized. That is, a parameterized method can operate on a variety of data and be used in a number of slightly different situations. To show this point, let’s use a very simple example. Here is a method that returns the square of the number 10: int square() { return 10 * 10; } 30
  • 31. Method That Takes Parameter • While the previous method does, indeed, return the value of 10 squared, its use is very limited. • However, if we modify the method so that it takes a parameter, as shown next, then we can make square( ) much more useful. int square(int i) { return i * i; } 31
  • 32. Box Program • Thus, a better approach to setting the dimensions of a box is to create a method that takes the dimension of a box in its parameters and sets each instance variable appropriately. • This concept is implemented by the following program: 32
  • 33. Box Program… // This program uses a parameterized method. class Box { double width; double height; double depth; // compute and return volume double volume() { return width * height * depth; } 33
  • 34. Box Program… // sets dimensions of box void setDim(double w, double h, double d) { width = w; height = h; depth = d; } } 34
  • 35. Box Program… class BoxDemo5 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // initialize each box mybox1.setDim(10, 20, 15); mybox2.setDim(3, 6, 9); 35
  • 36. Box Program… // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } } 36
  • 37. Constructor • A constructor is a method that executes automatically whenever an object is created. • It has the same name as the class in which it is created. • Constructors have no return type, not even void. This is because the implicit return type of a class’ constructor is the class type itself. 37
  • 38. Example class Box { double width; double height; double depth; // This is the constructor for Box. Box() { System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } // compute and return volume double volume() { return width * height * depth; } } 38
  • 39. Example… class BoxDemo6 { public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } } 39
  • 40. Parameterized Constructors • While the Box( ) constructor in the previous example does initialize a Box object, but it is not very useful because all boxes have the same dimensions. • Actually we need a way to construct Box objects of various dimensions. The easy solution is to add parameters to the constructor. 40
  • 41. Example Program class Box { 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 double volume() { return width * height * depth; } } 41
  • 42. Example Program… class BoxDemo7 { public static void main(String args[]) { // 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); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } } 42
  • 43. Output The output from this program is shown here: Volume is 3000.0 Volume is 162.0 43