Chapter 05 - Objects and Classes in Java

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 51

Object Oriented Programming

19CSE (2nd Semester)


Chapter#05: Objects and Classes

1
Outline
Concept of Class
Class members
General form of a Java class
Fields
Fields Declaration
Methods
Method Definition
Method invocations
Concept of Objects
Access Control: Data Hiding and Encapsulation
Constructors
Keyword this
Garbage collection
Finalize method
Method overloading
Constructor overloading
Parameter passing
Recursion
Java Example programs 2
Concept of Class
 A class is essential element of Object Oriented Programming
 A class is the template or prototype that defines the states
and the behaviors common to all objects of a certain kind.
 It is the collection of objects of similar type
 When a class is created it means new data type has been
created.
 Classes are user define data types and behave like built in
types of programming language.
 If you are creating class, you are doing encapsulation.
Encapsulation simply means binding object state(fields)
and behaviors (methods) together in to single unit.
Class Members
 A class can have three kinds of members:
 fields:
That hold the object’s state
data variables which determine the status of the class or
an object
 methods:
that describe the object’s behaviors
executable code of the class built from statements. It
allows us to manipulate/change the status of an object or
access the value of the data member
 nested classes and nested interfaces [optional]
General form of a Java Class
 In general, a simple class declarations can include these
components, in order:
 Modifiers: A class can be public or has default access
 Class name: The name should begin with a capital letter
(capitalized by convention).
 Superclass(if any): The name of the class’s parent (superclass),
if any, preceded by the keyword extends. A class can only
extend (subclass) one parent.
 Interfaces(if any): A comma-separated list of interfaces
implemented by the class, if any, preceded by the keyword
implements. A class can implement more than one interface.
 Body: The class body surrounded by braces, { }.
 In the body of class we define states and behaviors which are
common to all objects of that class.
Fields
 In the body of class we define states and behaviors which are
common to all objects of that class.
 define the variables/fields that hold the object’s state
 define the methods that describe the object’s behaviors
Field Declaration
 field declarations can be preceded by different modifiers
 access control modifiers
 static/non static (by default)
 final
 Followed type name followed by the field name, and optionally
an initialization clause
 primitive data type or Object reference
 boolean, char, byte, short, int, long, float, double
Fields
Fields Declaration
 Access control modifiers
 private: private members are accessible only in the class
itself
 package: package members are accessible in classes in
the same package and the class itself
 protected: protected members are accessible in classes
in the same package, in subclasses of the class, and in
the class itself
 public: public members are accessible anywhere the
class is accessible
Fields
Fields Declaration
 Non static(instance) data members
 Each object contains separate copy of these variables. This is
known as non static or instance data members.
 By default (when we don’t specify static), the data member is
to be considered as instance data member.
 can be accessed directly in the class itself
 from outside the class, public/package non-static fields must
be accessed through an object reference.
 From outside the class, private/protected data members can
be accessed through methods
 Can not be accessed directly i.e. through an object reference
Fields
Fields Declaration
 Static data members
 only one copy of the static field exists, shared by all objects of
this class
 can be accessed directly in the class itself
 access from outside the class must be preceded by the class
name as follows
System.out.println(Pencil.nextID);
 or via an object belonging to the class
Fields
Field Declaration
Final (optional if it is required)
 once initialized, the value cannot be changed
 often be used to define named constants
 static final fields must be initialized when the class is
initialized
 non-static final fields must be initialized when an object
of the class is constructed
Methods
Method Definition
1) method header
 consists of modifiers (optional), return type,
method name, parameter list and a throws clause
(optional)
 types of modifiers
 access control modifiers
 abstract
 the method body is empty. E.g.
abstract void sampleMethod( );
 Used within in abstract classes(classes cannot be instantiated)
 static
 represent the whole class, no a specific object
 can only access static fields and other static methods of the same class
 final
 cannot be overridden in subclasses

2) method body
Methods
Method Invocation/Calling
 invoked as operations on objects/classes using the dot ( . )
operator
reference.method(arguments)
 static method:
Outside of the class: “reference” can either be the class name or an
object reference belonging to the class
Inside the class: “reference” can be ommitted
 non-static method:
“reference” must be an object reference
Objects
 An object is an instance of a class
 It is a basic unit of Object Oriented Programming and represents
the real life entities.  
 Once a class is created/already exist, we can create many objects,
which interact by invoking methods. An object consists of :
 State: represents the data (value) /attributes of an object. It also
reflects the properties of an object.
 Behavior: represents the behavior (functionality)/operation of an
object such as deposit, withdraw, etc. it is represented by methods
of an object.
 Identity: It gives a unique name to an object and enables one object to
interact with other objects.
 An object can perform only those operations/behaviors/actions
which are defined within the body of the class.
 New keyword is used to create an object of particular class.
 The new keyword is used to allocate memory at runtime.
Lamp Class
Every object of class lamp can either be set either ONN or Off.
The lamp object can perform two operations/actions.
turnOn(set) operation will set the isOn=true and turnOff(reset)
operation will retset the isOn=False.

 State(s):
 isOn=true/false
 Behaviors:
 turnOn( )
 turnOff( )
// java program to create and test Lamp class
class Lamp
{ class Main
boolean isOn; {
public static void main(String[] args)
void turnOn()
{
{ // create objects l1 and l2
// initialize variable with value true Lamp l1 = new Lamp();
isOn = true; Lamp l2 = new Lamp();
System.out.println("Light on? " + isOn); // call methods turnOn() and turnOff()
} l1.turnOn();
l2.turnOff();
void turnOff()
}
{ }
// initialize variable with value false
isOn = false;
System.out.println("Light on? " + isOn);
}
}
Ways to initialize object
There are 3 ways to initialize object in Java.
1) By reference variable
2) By method
3) By constructor

Example Class: Box


The 3D Box class
 The 3d box contains three dimension: (data members)
 length, width and height of the box.
 This class contains : (methods)
 various constructors to initialize the dimensions of the box
 volume method to calculate the volume of the box
 get method to get dimensions of the box from user
 and show method to display dimensions of the box

3D Box class
 State(s): (Attributes)
 Length, width, height
 Behaviors: (Methods)
 Set,volume,get,show
class Box // compute and return volume
{ double volume()
double width; {
double height; return width * height * depth;
double depth; }
// constructor used when all dimensions specified void showBox()
Box(double w, double h, double d) {
{ System.out.println("The width="+width);
width = w; System.out.println("The height="+height);
height = h; System.out.println("The depth="+depth);
depth = d; }
} void getBox()
// constructor used when no dimensions specified {
Box() Scanner kb=new Scanner(System.in);
{ System.out.println("Enter width");
width = -1; // use -1 to indicate width=kb.nextDouble();
height = -1; // an uninitialized System.out.println("Enter height");
depth = -1; // box height=kb.nextDouble();
} System.out.println("Enter depth");
// constructor used when cube is created depth=kb.nextDouble();
Box(double len) }
{ }// closing brace for class body
width = height = depth = len;
}
public class BoxDemo
{
public static void main(String []args)
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
The Circle class
 The Circle contains three dimension: (data members)
 xCenter,yCenter //location of a circle.
 Radius // radius of a circle
 Count static member
 This class contains : (methods)
 various constructors to initialize the cirlce
 cirlceArea to calculate area of a circle
 circleCircum to calculate circumference of a circle
 getCircle method to get dimensions of the circle from user
 and showCircle method to display dimensions of the circle
 Static method getCount to determine number of circle objects are created

Cirlce class
 State(s): (Attributes)
 xCenter,yCenter,Radius,count
 Behaviors: (Methods)
 Set,Area,Circum,get,show ,getcount
class Circle
{ void showCircle()
private int x; {
private int y; System.out.println();
double radius; System.out.println("x="+x);
private static double pi=3.14; System.out.println("y="+y);
private static int count=0; System.out.println("radius="+radius);
//constructors
Circle() }
{ void getCircle()
x=0; {
y=0; Scanner input=new Scanner(System.in);
radius=0.0; System.out.println();
count++;
System.out.print("Enter x=");
}
x=input.nextInt();
Circle(int x,int y,double rad)
System.out.print("Enter y=");
{
this.x=x; y=input.nextInt();
this.y=y; System.out.print("Enter radius=");
radius=rad; radius=input.nextDouble();
count++; }
} static int getCount()
double areaCircle() {
{ return count;
return (pi*radius*radius); }
} }
double circumCircle()
{
return (2*pi*radius*radius);
}
import java.util.Scanner;
public class DemoCircle
{
public static void main(String[] args)
{
System.out.println("The number of circles created="+Circle.getCount());
Circle c1=new Circle(4,5,2.3)
System.out.println("The number of circles created="+Circle.getCount());
Circle c2=new Circle();
System.out.println("The number of circles created="+Circle.getCount());
System.out.println("Enter dimensions of circle c2");
c2.getCircle();
System.out.println("circle c1=");
c1.showCircle();
System.out.println("its area is "+c1.areaCircle());
System.out.println("its circumference is "+c1.circumCircle());
System.out.println("circle c2=");
c2.showCircle();
System.out.println("its area is "+c2.areaCircle());
System.out.println("its circumference is "+c2.circumCircle());
}
}
Student Class
Write/create a Java class Student to meet the following
specification. - The class should be able to support a 6 digit student
ID/rollno, student name, marks for 5 subjects. You should have
methods to set and get each of the attributes, methods to set and
get marks of the student and methods to calculate the average,
percentage and grade for the student. Write a tester program to
test your class. You should create 2 or 3 students and write code to
test the class
Student Class
 State(s): (Attributes)
 Roll#, name, marks[5]
 Behaviors: (Methods)
 setStudent, getStudent, showStudent, calcPercentage, calcGrade,
 clacAverage, setMarks, getMarks
class Student int minMarks()
{ {
String rollno; int min=marks[0];
String name; for(int i=1;i<marks.length;i++)
int []marks=new int[5]; if(min>marks[i])
//constructors min=marks[i];
Student(String rn,String nm) return min;
{ }
rollno=rn; int maxMarks()
name=nm; {
int[]mrks={0,0,0,0,0}; int max=marks[0];
marks=mrks; for(int i=1;i<marks.length;i++)
} if(max<marks[i])
Student(String rn,String nm,int[]mrks) max=marks[i];
{ return max;
rollno=rn; }
name=nm; double calcAverage()
marks=mrks; {
} double tmarks=0;
void setMarks(int[]mrks) for(int i=0;i<marks.length;i++)
{ tmarks+=marks[i];
marks=mrks; double avg=(tmarks)/5;
} return avg;
void getMarks() }
{ double calcPercent()
Scanner input=new Scanner(System.in); {
for(int i=0;i<marks.length;i++) double tmarks=0;
{ for(int i=0;i<marks.length;i++)
System.out.print("En[ter marks for subject"+(i+1)+">>"); tmarks+=marks[i];
marks[i]=input.nextInt(); double per=(tmarks/500)*100;
} return per;
} }
char calcGrade()
{
double per=calcPercent();
char grade='E';
if (per<50)
grade='F';
if(per>=50 & per<60)
grade='D';
if(per>=60 & per<70)
grade='C';
if(per>=70 & per<80)
grade='B';
if(per>=80)
grade='A';
return grade;
}
void studentSummary()
{
System.out.println("Name="+name);
System.out.println("Rollno="+rollno);
System.out.println("Marks of the student are");
for(int i=0;i<marks.length;i++)
System.out.print(marks[i]+",");
System.out.println("Minimum marks in the subjects ="+minMarks());
System.out.println("Maximum marks in the subjects ="+maxMarks());
System.out.println("Average marks ="+calcAverage());
System.out.println("Percentage="+calcPercent()+"%");
System.out.println("Grade="+calcGrade());
}
} // closing brace for class body
// main class or application class for student
import java.util.Scanner;
public class MainStudent
{
public static void main(String []args)
{
Student st1=new Student("19cs01","Aslam");
int[] mrks={50,60,70,80,75};
st1.setMarks(mrks);
Student st2=new Student("19CS02","Ahmed");
System.out.println("Enter marks for student st2");
st2.getMarks();
System.out.println("the percentage of student st1 is "+st1.calcPercent()+"%");
System.out.println("and your grade is "+st1.calcGrade());
System.out.println("the percentage of student st2 is "+st2.calcPercent()+"%");
System.out.println("and your grade is "+st2.calcGrade());
System.out.println("Student summary for st1=");
st1.studentSummary();
System.out.println("Student summary for st2=");
st2.studentSummary();
}
}
The Bank Account class
 The Circle contains three attributes for each account holder:
(data members)
 Balance
 Account number
 Name
 This class contains : (methods)
 various constructors to initialize data members
 Deposit method to deposit amount
 Withdraw method to withdraw amount
 Check balance method to determine current balance
 Transfer method to transfer amount to another account
 infoAccount method to display information of account holder
class BankAccount
{
// These are different for each account
private double balance;
private int accountNumber;
private String name;

// This is shared by all accounts, so it's static


private static int lastAccountNumber = 100;
private static int count=0;

// This is a constructor: no return type (void, boolean etc) and has the same name as the class.
public BankAccount(String nm,double intialBalance)
{
balance = intialBalance;
name=nm;
accountNumber = lastAccountNumber + 1;
lastAccountNumber = accountNumber;
System.out.println("Your account has been created");
++count;
}
public void deposit(double depositAmount)
{
balance += depositAmount;
System.out.println("Your current balance is "+balance);
}
public static int getCount()
{
return count;
}
public void withdraw(double withdrawAmount)
{
if (withdrawAmount > balance)
System.out.println("can not withdraw. Insufficient amount");
else
{
balance-=withdrawAmount;
System.out.println("Your balance is "+balance);
}
}
public void checkBalance()
{
System.out.println("Your current balance is "+balance);
}
public void infoAccount()
{
System.out.println("name="+name);
System.out.println("Account number="+accountNumber);
System.out.println("Balance="+balance);
}
public void transfer(BankAccount other, double amount)
{
if(amount<balance)
{
balance-=amount;
other.balance+=amount;
System.out.println("Your balance is "+balance);
}
else
System.out.println("Can not transfer amoutnt. In sufficient amount in your account");
}
} // end of the class
public class BankDemo
{
public static void main(String[] args)
{
System.out.println("The number of accounts have been created are"+BankAccount.getCount());
BankAccount acc1=new BankAccount("Aslam",500);
System.out.println("The number of accounts have been created are"+BankAccount.getCount());
acc1.infoAccount();
BankAccount acc2=new BankAccount("Fareed",300);
System.out.println("The number of accounts have been created are"+BankAccount.getCount());
acc2.infoAccount();
BankAccount acc3=new BankAccount("Faisal",800);
System.out.println("The number of accounts have been created are"+BankAccount.getCount());
acc3.infoAccount();
acc1.deposit(1000);
acc2.withdraw(200);
acc3.transfer(acc2, 500);
acc1.withdraw(2000);
}
}
Stack Class
 A stack is a LIFO (Last in first out) system. In stack insertion and
deletion is take place on top of the stack. In stack item stored last
will be retrieved first :
 Therefore this class contains data members:
 Top // a variable top
 Stk[] //an array
 This class contains : (methods)
 A constructor to initialize top equal to -1
 Push method to insert an item on top of the stack
 Pop method to delete an item from top of the stack
 Show stack method to display contents of the stack
Class for Complex Numbers
 A complex number is combination of two parts; a+ib where a is
real part and b is the imaginary part.
 Therefore this class contains two data members:
 Real
 imaginary
 This class contains : (methods)
 overloaded constructors to initialize complex numbers
 getComplex method to get complex number from user
 showComplex method to display complex number in the form:
a+jb
 Overloaded methods addComplex to add two complex
numbers
 Overloaded methods subComplex to perform subtraction
between two complex numbers
The Sphere class
 A sphere is a geometrical object in three-dimensional space that
is the surface of a ball (circular objects in three dimensions)
 analogous to the circular objects in two dimensions, where a
"circle" circumscribes its "disk").
 These are also referred to as the radius and center of the sphere,
respectively. Therefore this class contains data members:
 xCenter,yCenter,cCenter // 3D dimensions of the center
 Radius // radius of sphere
 This class contains : (methods)
 overloaded constructors to initialize Sphere
 Volume method to calculate the volume of the sphere
 getSphere method to get dimensions of sphere from user
 showSphere method to display dimensions of sphere object
import java.util.Scanner;
public class DemoCircle
{
public static void main(String[] args)
{
System.out.println("The number of circles created="+Circle.getCount());
Circle c1=new Circle(4,5,2.3)
System.out.println("The number of circles created="+Circle.getCount());
Circle c2=new Circle();
System.out.println("The number of circles created="+Circle.getCount());
System.out.println("Enter dimensions of circle c2");
c2.getCircle();
System.out.println("circle c1=");
c1.showCircle();
System.out.println("its area is "+c1.areaCircle());
System.out.println("its circumference is "+c1.circumCircle());
System.out.println("circle c2=");
c2.showCircle();
System.out.println("its area is "+c2.areaCircle());
System.out.println("its circumference is "+c2.circumCircle());
}
}
Access Control: Data Hiding and Encapsulation
 Java provides control over the visibility of variables and
methods.
 Encapsulation, safely sealing data within the capsule of
the class Prevents programmers from relying on details
of class implementation, so you can update without
worry
 Helps in protecting against accidental or wrong usage.
 Keeps code elegant and clean (easier to maintain)
Constructors
 A constructor is a special method that contains same name as name
of the class.
 Used to initialize the instance variables of an object.

 It is called immediately after the object is created but before the


new operator completes.
 it is syntactically similar to a method:
 It is a special method

 it has the same name as the name of its class


 it is written without return type; the default return type of a
class.
 It may contains arguments
Constructors types
 Types of constructors
 Default constructor
 Parameterized constructor
 Copy constructor
 When the class has no constructor, the default constructor automatically
initializes all its instance variables with zero.
 We don’t have to create this type of constructor.
 A constructor that has parameters is called a parameterized constructor in
Java. We use the parameterized constructor when we want to provide
different values to the distinct objects.
 Copy constructor in Java class is a special type of constructor that takes the
same class as an argument. A copy constructor is used to provide a copy of the
specified object.
Constructors types Examples
Suppose we have created Box class this class contains three data members; width,
height, depth. Following are the examples of parameterized constructors
Box(double w, double h, double d)
{ Box(double len)
{
width = w;
width = height = depth = len;
height = h; }
depth = d; In main method
} Box b=new Box(2.1);
In method
Box b=new Box(1.1,1.2,1.3);
Following is an example of copy constructor. In main method
Box(Box ob) Box b1=new Box(1.1,2.1,3.1);
{ Box b2=new Box(b1);
width=ob.width;
height=ob.width;
depth=ob.depth;
}
Keyword this
 Can be used by any object to refer to itself in any class method.
Typically used to Box(double width, double height, double depth)
{
Avoid variable name collisions this.width = width;
this.height = height;
Pass the receiver as an argument this.depth = depth;
}
Chain constructors
 this is a reference variable that refers to the current object. In
java this keyword is used:
 this can be used to refer current class instance variable.
 this can be used to invoke current class method (implicitly)
 this() can be used to invoke current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
 this can be used to return the current class instance from the method.
Garbage Collection
 Garbage collection is a mechanism to remove objects from
memory when they are no longer needed.
 Garbage collection is carried out by the garbage collector:

1) The garbage collector keeps track of how many references an


object has.
2) It removes an object from memory when it has no longer any
references.
3) Thereafter, the memory occupied by the object can be allocated
again.
4) The garbage collector invokes the finalize method.
finalize() Method
 A constructor helps to initialize an object just after it has been
created.
 In contrast, the finalize method is invoked just before the object is
destroyed:

1) implemented inside a class as:


protected void finalize() { … }
2) implemented when the usual way of removing objects from
memory is insufficient, and some special actions has to be
carried out
Method Overloading
 It is legal for a class to have two or more methods with the same
name.
 However, Java has to be able to uniquely associate the invocation
of a method with its definition relying on the number and types
of arguments.
 Therefore the same-named methods must be distinguished:

1) by the number of arguments, or


2) by the types of arguments
 Overloading and inheritance are two ways to implement
polymorphism.
Example: Overloading
class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}
void test(int a)
{
System.out.println("a: " + a);
}
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
}
double test(double a)
{
System.out.println("double a: " + a); return a*a;
}
}
class Box Constructor Overloading
{
double width, height, depth;
Box(double w, double h, double d)
{
width = w; height = h; depth = d;
}
Box()
{
width = -1; height = -1; depth = -1;
}
Box(double len)
{
width = height = depth = len;
}
double volume()
{
return width * height * depth;
}
}
Parameter Passing
 Two types of variables:

` 1) simple types

` 2) class types
 Two corresponding ways of how the arguments are passed to
methods:
1) by value a method receives a cope of the original value;
parameters of simple types
2) by reference a method receives the memory address of the
original value, not the value itself; parameters of class types
Recursion
 A recursive method is a method that calls itself:

1) all method parameters and local variables are allocated on the


stack

2) arguments are prepared in the corresponding parameter


positions
3) the method code is executed for the new arguments
4) upon return, all parameters and variables are removed from the
stack
5) the execution continues immediately after the invocation point
public class ItReFactorial
{ Example: Recursion
public static void main(String[] args)
{
Factorial f = new Factorial();
System.out.println("Factorial of 5 (iterative method) is "+f.factI(5));
System.out.println("Factorial of 5 (Recursive method) is "+f.factR(5));
}
}
class Factorial // Recursive
{
int factR(int n)
{
if (n==1) return 1; output
return factR(n-1) * n; Factorial of 5 (iterative method) is 120
}
int factI(int n)
Factorial of 5 (Recursive method) is 120
{
int fact=1;
for(int i=1;i<=n;i++)
fact=fact*i;
return fact;
}
}
Student Class
 State(s):
 Roll#, name, age, marks
 Behaviors:
 setStudent, getStudent, showStudent, calcPercentage, calcGrade
Complex Numbers
 State(s):
 Real, imaginary
 Behaviors:
 Set, get,show,add,mul,sub,div,convPolar

2D Point Class
 State(s):
 X,y
 Behaviors:
 translate,scale,disance
3D Box class
Rectangle Class
 State(s):
 State(s):
 Length, width, height
 Length, width
 Behaviors:
 Behaviors:
 Set, get,volume
 Set,get, Area

Stack Class Circle Class


 State(s):  State(s):
 Array, top  Length, width,radius
 Behaviors:  Behaviors:
 Initialize,Push,Pop  Set,get,show,Area,Circumference

Queue Class Sphere Class


 State(s):  State(s):
 Array, front, rear  Radius, xCenter,yCenter,zCenter
 Behaviors:  Behaviors:
 Initialize,insert,delete  Set, get, show, volume
class Stack
{
int stck[] = new int[10];
int tos; class TestStack
// Initialize top-of-stack {
Stack() public static void main(String args[])
{ {
tos = -1; Stack mystack1 = new Stack();
} Stack mystack2 = new Stack();
// Push an item onto the stack // push some numbers onto the stack
void push(int item) for(int i=0; i<10; i++)
{ mystack1.push(i);
if(tos==9) for(int i=10; i<20; i++)
System.out.println("Stack is full."); mystack2.push(i);
else // pop those numbers off the stack
stck[++tos] = item; System.out.println("Stack in mystack1:");
} for(int i=0; i<10; i++)
// Pop an item from the stack System.out.println(mystack1.pop());
int pop() System.out.println("Stack in mystack2:");
{ for(int i=0; i<10; i++)
if(tos < 0) { System.out.println(mystack2.pop());
System.out.println("Stack underflow."); }
return 0; }
}
else
return stck[tos--];
}
}
class Box
{
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d)
{ class DemoBox
width = w; {
height = h; public static void main(String args[])
depth = d; {
} // create boxes using the various constructors
// constructor used when no dimensions specified Box mybox1 = new Box(10, 20, 15);
Box() Box mybox2 = new Box();
{ Box mycube = new Box(7);
width = -1; // use -1 to indicate double vol;
height = -1; // an uninitialized // get volume of first box
depth = -1; // box vol = mybox1.volume();
} System.out.println("Volume of mybox1 is " + vol);
// constructor used when cube is created // get volume of second box
Box(double len) vol = mybox2.volume();
{ System.out.println("Volume of mybox2 is " + vol);
width = height = depth = len; // get volume of cube
} vol = mycube.volume();
// compute and return volume System.out.println("Volume of mycube is " + vol);
double volume() }
{ }
return width * height * depth;
}
}

You might also like