0% found this document useful (0 votes)
5 views

2 Classes, Methods, and Objects

Oop

Uploaded by

hasibshahriar04
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

2 Classes, Methods, and Objects

Oop

Uploaded by

hasibshahriar04
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Classes, Methods and Objects

Class Fundamentals

 A class is a template for an object.


 An object is an instance of a class.
 Define a new data type.
 Once define this new data type is used
to create an object of that type.
The Structure of a class
class classname {
type instance-variable1;
type instance-variable1;
//...
type instance-variableN;

type methodname1(parameter-list){
//body of the method
}
type methodnameN(parameter-list){
//body of the method
}
}
 The data/variable within the class is called
instance variable.
 Each object has its own copy of variable.
 The code is contained within the method.
 The method and instance variable is defined
within the class is called member of the
class. that is, things that you access with .
 The variable of one object is separate and
unique from the variable of the other object.
class Box {
double width;
double height;
double depth;
}
To create an object of type Box:
 Box mybox = new Box();
 Now mybox will be an instance of Box.
 To access the member of the mybox object
outside the class
 mybox.width=100;
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;

// assign values to mybox's instance variables


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

// compute volume of box


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

System.out.println("Volume is " + vol);


}
}
Here two class file are created
1.BoxDemo
2.Box

 These two class may contain in two different


files.
 javac Box.java BoxDemo.java
There can only be one public class per file. The filename should also match the name of this public class (e.g., MyClass.java for a class named MyClass).
This class is accessible from other packages. You can have multiple classes declared without the public keyword.
These classes are considered package-private and can only be accessed by other classes within the same package.
Declaring Objects

 Creating an object is a two steps process:


 Declare a variable of the class type
 It is simple a variable that can refer to an object
 Acquire an actual copy of the object and assign it to that
variable.
Keyword
 new operator is used to allocate the memory for an
object and return a reference to it.
 reference means the address of the object allocated by
new.
Box b1 = new Box(); you create a new instance of the Box class in memory and assign its reference to the variable b1.
This means b1 now refers to the actual Box object.

Box b2 = b1; copy the reference of b1 to b2

.......

b1 = null; b1 no longer refers to any specific object. It becomes a reference that doesn't point anywhere.
The original Box object itself might still exist in memory until it's garbage collected, but you can't access it through b1 anymore.

 When you assign one object reference


variable, you are not creating a copy of the
object, you only making a copy of the
reference.
class Box {
double width;
double height;
double depth;

// display volume of a box


void calculateVolume() {
System.out.println("Volume is “ +width * height * depth);
}
}
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();

// 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;

// display volume of first box


mybox1.calculateVolume();
Volume is 3000.0
// display volume of second box Volume is 162.0
mybox2.calculateVolume();
}
}
Constructor

Using Constructor is a must to while creating an object

 A constructor initializes an object


immediately upon creation.
 It has the same name as the class in whice it
resides.
 Automatically called after the object is
created.
class Box {
double width;
double height;
double depth;

// This is the constructor for Box.


Box() {
System.out.println("Constructing Box"); Printing inside a constructor

width = 10;
height = 10;
depth = 10;
}

// compute and return volume


double volume() {
return width * height * depth;
}
}
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);
Output:
// get volume of second box Whenever a object is crated
construtor gets called and prints
Constructing Box
(executes the printing method)
vol = mybox2.volume();
Constructing Box
System.out.println("Volume is " + vol);
Volume is 1000.0
}
Volume is 1000.0
}
 Box mybox1 = new Box();

 The constructor is the class Box is being


called.
 When no constructor is defined, java creates
a default constructor and initialized all the
instance variable to zero.
Therefore, In the previous example, the volume will be 0.0 (code saved)
Parameterized Constructor
/* Here, Box uses a parameterized constructor to initialize the dimensions of a box.*/
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;
}
}
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);
}
}
The this Keyword
 This keyword can be used inside any method to
refer the current object.
 Every object can access a reference to itself with
this.
 Use this to resolve name-space collisions.

Box(double width, double height, double depth) {


this.width = width;
this.height = height;
this.depth = depth;
Local variable/
} formal parameter
Garbage Collection

 Handle de-allocation of memory that is


occupied by object.
exists
 When no references to an object exits the
memory is automatically be freed.
The Finalize Method Built-in

 If an object is holding some non-java resources such


as file handler.
 You want to make sure these resources must be freed
before an object is destroyed.
 Define specific actions that will occur when an object is
just about to be reclaimed by garbage collection.
 The structure of finalize method is:
protected void finalize() Key points:
1. Not guaranteed
2. Unpredictable timing
{ 3. Not an alternative to proper resource management

//finalization code
}
 Prevents access to finalize() by code outside of the
class.
Arrays

 An array is a group of like-typed variables


that are referenced by a common name.
 A specific element of an array is accessed by
its index.
One dimensional Arrays
 The general form of one dimensional array
declaration is:
 type var_name[];
 Example:
 int month_days[];
 Actually no array is exists.
 This is a reference variable that can hold the address
of the integer type array.
 month_days = new int[12];
 Allocates a 12 element array of integer and link
them to the month_days.
 Array can be initialized when they are declared
Like C

class AutoArray {
public static void main(String args[]) {
Size can't be writen (we could do this in C)
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31,
30, 31, 30, 31 };
System.out.println("April has " + month_days[3] + "
days.");
}
}
Multidimensional Arrays
 int twoD[][] = new int[4][5];
 This allocates a 4 by 5 array and assigns it to twoD.
 In Multidimensional array
 you only need to the first dimension (leftmost). (Row)
 You can allocate the remaining dimension separately.

int twoD[][] = new int[4][];


twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
Alternative array declaration syntax
 int a1[] = new int[3];
 int [] a2 = new int [3];
 Array are implemented as objects
 Using length instance variable we can found the
number of element that an array hold.
For 2D array, length will be number of rows
class Length { To get number of columns, we need to write => array_name[index_of_row]

public static void main(String args[]) {


int a1[] = new int[10];
int a2[] = {3, 5, 7, 1, 8, 99, 44, -10};
int a3[] = {4, 3, 2, 1};
Not a method, so not length() but length
System.out.println("length of a1 is " + a1.length);
System.out.println("length of a2 is " + a2.length);
System.out.println("length of a3 is " + a3.length);
}
}
Strings
 Probably the most common used class.
 Every string you created is actually an object of
String class.
 Strings can be constructed a variety of ways:
String myString;
myString= "this is a test";
or
 String myString = "this is a test";
 System.out.println(myString);

 Using “+”, two strings can be concatenated


 String myString = "I" + " like " + "Java.";
Or, String myString= aString+bString;
// Demonstrating Strings.
class StringDemo {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1 + " and " + strOb2;

System.out.println(strOb1);
System.out.println(strOb2);
System.out.println(strOb3);
}
}
Also Compare => Directly using == [BE AWARE, there is no > / < / >= /..... for string (but != is available)]

 Some methods of String class:


 boolean equals(String object)
 int length() Not an instance variable like that of Array,
so not length but length()
 char charAt(int index) [Index starts from 0]
// Demonstrating some String methods.
class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;

System.out.println("Length of strOb1: " + strOb1.length());


System.out.println("Char at index 3 in strOb1: " + strOb1.charAt(3));

if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
Length of strOb1: 12
System.out.println("strOb1 != strOb2"); Index starts from 0
Char at index 3 in strOb1: s

if(strOb1.equals(strOb3)) strOb1 != strOb2


System.out.println("strOb1 == strOb3"); strOb1 == strOb3
else
System.out.println("strOb1 != strOb3");
}
}
Array of Strings
// Demonstrate String arrays.
class StringDemo3 {
public static void main(String args[]) {
String str[] = { "one", "two", "three" };
length of the array
for(int i=0; i<str.length; i++)
System.out.println("str[" + i + "]: " + str[i]);
}
}
Overloading Methods

 In Method overloading
 Two or more method within the same class share
the same name.
 But their parameter declarations are different.
 Overloaded methods must differ in the type or
the number of parameters.
 Methods may have different return type, but it is
not sufficient for method overloading.
// Demonstrate method overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}

// Overload test for one integer parameter.


void test(int a) {
System.out.println("a: " + a);
}

// Overload test for two integer parameters.


void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}

// overload test for a double parameter


double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;

// call all versions of test()


ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.2);
System.out.println("Result of ob.test(123.2): " + result);
}
}

Output:
No parameters
a: 10
a and b: 10 20
double a: 123.2
Result of ob.test(123.2): 15178.24
Automatic Type Conversion
// Automatic type conversions apply to overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}

// Overload test for two integer parameters.


void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}

// overload test for a double parameter and return type


void test(double a) {
System.out.println("Inside test(double) a: " + a);
}
}
class Overload { One Interface, Multiple
public static void main(String args[]) { methods
OverloadDemo ob = new OverloadDemo(); In c, there are abs(), fabs(),
int i = 88; labs() which return the absolute
value of integer, float and long.
But in java abs() method of Math
ob.test(); class can return absolute value
ob.test(10, 20); of all data type using method
overloading.

ob.test(i); // this will invoke test(double)


ob.test(123.2); // this will invoke test(double)
}
}

Output:
No parameters
a and b: 10 20
Inside Test( double) a :88
Inside Test (double) a: 123.2
Overloading Constructor
/* Here, Box defines three constructors to initialize
the dimensions of a box various ways.*/
class Box {
double width;
double height;
double depth;

// constructor used when all dimensions specified


Box(double w, double h, double d) {
width = w; // constructor used when cube is
height = h; created
depth = d; Box(double len) {
} width = height = depth = len;
}
// constructor used when no dimensions specified
Box() { // compute and return volume
width = -1; // use -1 to indicate double volume() {
height = -1; // an uninitialized return width * height * depth;
depth = -1; // box }
} }
class OverloadCons { Output:
public static void main(String args[]) {
Volume of mybox1 is 3000.0
// create boxes using the various constructors
Volume of mybox2 is –1.0
Box mybox1 = new Box(10, 20, 15);
Volume of mycube is 343.0
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);
}
}
Objects as Parameter
// Objects may be passed to methods.
class Test {
int a, b;

Test(int i, int j) {
a = i;
b = j;
}

// return true if o is equal to the invoking object


boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
}
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);

System.out.println("ob1 == ob2: " + ob1.equals(ob2));

System.out.println("ob1 == ob3: " + ob1.equals(ob3));


}
}

Output:
ob1 == ob2: true
ob1 == ob3: false
Call-by-Reference
 A reference to an argument is passed to the parameter.
 Used to access the actual argument specified in the call
 In Java
 This is done by passing an object
 Object are passed by reference
Primitive data types are always passed by value.
class Test { Objects, arrays, and strings are passed by reference (a copy of the reference, not the object itself).
Modifications made through the reference variable within the method affect the original object.
int a, b; Java doesn't have direct pointers for primitive data types.
Wrapper classes and modifying objects passed by reference can simulate call by reference
behavior for primitives, but with limitations.
Test(int i, int j) {
a = i;
b = j;
}

// pass an object
Don't get confused; you can pass an object of the same class as where (class) it's written
void meth(Test o) {
o.a *= 2;
o.b /= 2;
}
}
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);

System.out.println("ob.a and ob.b before call: " +


ob.a + " " + ob.b);

ob.meth(ob);

System.out.println("ob.a and ob.b after call: " +


ob.a + " " + ob.b);
}
}

Output:
When a simple type is passed to
Ob.a and ob.b before call: 15 20 a method, it is done by use of
Ob.a and ob.b after call: 30 10 call-by-value. Objects are passed
by use of call-by-reference.
Returning Objects
// Returning an object.
class Test {
int a;

Test(int i) {
a = i;
}

Test incrByTen() {
Test temp = new Test(a+10);
return temp;
}
}
class RetOb {
Output:
public static void main(String args[]) {
Ob1.a: 2
Test ob1 = new Test(2);
Ob2.a: 12
Test ob2;
Ob2.a after second increase: 22

ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);

ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: "
+ ob2.a);
}
}

 Each time incrByTen() is invoked, a new object is


created and a reference to it is returned to the
calling routine.
Access Control
 Control what parts of a program can access the
member of a class. aka Access Modifier
 Three access specifier: public, private, protected.
 When a member is declared as public
 The member is accessed by any other code in your
program
 When a member is declared as private
 The member is only access by the other member of that
class
 When no access specifier is declared, It is by
default declared as public.
/* This program demonstrates the difference between public and private.*/

class Test { // This is not OK and will cause an error


int a; // default access // ob.c = 100; // Error!
public int b; // public access
private int c; // private access // You must access c through its methods
ob.setc(100); // OK
// methods to access c
void setc(int i) { // set c's value System.out.println("a, b, and c: " + ob.a + " " +
c = i; ob.b + " " + ob.getc());
} }
int getc() { // get c's value }
return c;
}
}

class AccessTest {
public static void main(String args[]) {
Test ob = new Test();

// These are OK, a and b may be accessed directly


ob.a = 10;
ob.b = 20;
Static Keyword
 A class member is only accessed when the
object or instance the class is created.
 It is possible to create a class member
without reference to a specific instance.
 When a member is declared as static it is
possible to access those member without
creating any object of that class.
 Instance variable which are declared as static
is behaved like global variable.
block

 Static have several restrictions:


 They can only call other static methods.
 They must only access static data.
 They cannot refer to this or super in any way.
// Demonstrate static variables, methods, and blocks.
class UseStatic {
static int a = 3;
public static void main(String args[])
static int b; {
static void meth(int x) { meth(42);
}
System.out.println("x = " + x);
System.out.println("a = " + a); }
System.out.println("b = " + b); Execute exactly once, when the class is
} loaded. Generally used to initializing static
variabls.
static {
System.out.println("Static block initialized."); Static block initialized.
x = 42
b = a * 4; a=3
} b = 12
 If you call a static method from outside its class
then use the following general form
 classname.method() When you are insited that class, you don't need to write
classname.method() ; instead write method() only

class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}

class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
Output:
System.out.println("b = " + StaticDemo.b);
a = 42
}
b = 99
}
Final Keyword
Just the same as const in C
 A variable can declared as final.
 Prevents its content from being modified.
 Behave like a constant
Lowercase, not uppercase

 final int FILE_NEW = 1;


 final int FILE_OPEN = 2;
 final int FILE_SAVE = 3;
 final int FILE_SAVEAS = 4;
 final int FILE_QUIT = 5;
Problem
 Create a class Employee that include three pieces
of information as instance variables- a first name
(type String), a last name (type String) and a
monthly salary (double). Your class should have a
constructor that initializes the three instance
variables. Provide a set and a get method for each
instance variable. If the monthly salary is not
positive, set it to 0.0. Write a test application
named EmployeeTest that demonstrate class Main Class
Employee’s capabilities. Create two Employee
objects and display each object’s yearly
salary.Then give each Employee a 10% raise and
display each Employee’s yearly salary again.
Problem
 Create a class Invoice that a hardware store might use to
represent an invoice for an item sold at the store. An
invoice should include four piece of information as
instance variables- a part number (type String), a part
description (type String), a quantity of an item being
purchased (type int) and a price per item (double). Your
class should have a constructor that initialized four
instance variables. Provide a get and set method for each
instance variable. In addition, provide a method name
getInvoiceAmount that calculate the invoice amount, then
return the amount as double value. If the quantity is not
positive, it should be set 0. If the price of per item is not
positive, it should be set 0.0. Write a test application
name InvoiceTest that demonstrate class Invoice’s
capabilities.
Problem
 Create a class called Date that include three
pieces of information as instance variable – a
month (type int), a day (type int) and a year
(type int). your class should have a
constructor that initializes the three instance
variables. Provided a set and a get method
for each instance variable. Provide a method
displayDate that displays the month, day and
year separated by forward slash(/). Write a
test application DateTest that demonstrate the
class’s capabilities.

You might also like