Object Oriented Programming - Chapter 2 - Classes
Object Oriented Programming - Chapter 2 - Classes
Compiled by Hashim S.
Introduction
A class is a logical framework or blue print or template of an
object.
Anything we wish to represent in Java must be encapsulated
in a class
defines the “state” and “behavior” of the basic program
components known as objects.
A class is a programmer defined data type
Objects use methods to communicate between them.
A class is a collection of fields (data) and methods
Fields: say what a class is (Things an object knows about itself).
Methods: say what a class does (Things an object can do).
2
Circle
centre
radius
circumference()
area()
The basic syntax for a class definition:
4
Adding Methods
A class with only data fields has no life. Objects created by
such a class cannot respond to any messages.
Methods are declared inside the body of the class but
code body:
[access modifier] ReturnType methodname ([parameters])
{
statements, including local variable declarations
}
The first line shows a method signature consisting of
access modifier - determines what other classes and subclasses
can invoke this method (e.g. Public, Private, and Protected).
5
Return Type - what primitive or class type value will return
from the invocation of the method.
If there is no value to return, use void for the return type.
Method Name – The name of the method in which the method
is identified with.
List of Parameters - the values passed to the method
The code body, delineated by the brackets, includes:
Local Variables - data variables can be declared and used
within the method.
Statements - the code to carry out the task for the particular
method
6
Adding Methods to Class Circle
public class Circle {
public double x, y; // centre of the circle
public double r; // radius of circle
7
Object
It is an instance of a class
Represents something with which we can interact in a program
Syntax:
8
An object uniquely identified by
its name
defined state,
represented by the values of its attributes in a particular time
Circle aCircle, bCircle;
aCircle, bCircle simply refers to a Circle object, not an
object itself.
aCircle bCircle
null null
Points to nothing (Null Reference) Points to nothing (Null Reference)
9
Creating objects of a class
aCircle = new Circle(); bCircle = new Circle() ;
bCircle = aCircle;
P Q P Q
10
Accessing Members of an object
We use ‘.’ (dot) operator together with the reference to an object
Syntax:
<ref. idn>.<member>;
Class DriverClass{
Public static void main(String args[]){
Circle c1 = new Circle();
c1.r = 2.3;
c1.area();
c1.circum();
}
}
Note:
String args[] parameter allows you to pass command-line arguments to your Java program when it is executed 11
Consider the already defined class Circle and define a driver
class
class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking method
double circumf = aCircle.circum();
System.out.println ("Radius=“ + aCircle.r " Area = “ + area);
System.out.println ("Radius = “ + aCircle.r + “Circum = “ +
circumf);
}
}
12
Exercise
Write a program that has two classes. The first class should
define a person’s name, age, and sex and display these data.
The second class should contain the main method.
13
Person Example
// Person class
class Person {
// Fields
String name;
int age;
char sex;
// Constructor
public Person(String name, int age, char sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
// Method to display person's details
public void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Sex: " + sex);
}
}
14
// MainClass class
public class MainClass {
public static void main(String[] args)
{
// Creating an instance of the Person class
Person person1 = new Person("John Doe", 25, 'M');
// Displaying person's details using the displayDetails method
System.out.println("Person's Details:");
person1.displayDetails(); } }
15
Person Example
class Person {
String name = “You”;
int age = 26;
void setName(String n) {
name = n;
}
String getName() {
return name;
}
void setAge(int a) {
age = a;
}
int getAge() {
return age;
}
}
Constructing Person Objects
To create an instance of the Person class with a name of
“Chala" and an age of 22
Person person = new Person();
person.setName(“Chala");
person.setAge(22);
Can we create a Person that has the name Chala and the
age of 22 from the moment it is created?
Answer: Yes!
Constructors
are used to initialize the instance variables (fields) of an object
Constructors are special methods used to construct an
instance of a class
Constructors are similar to methods, but with some important
differences
They have the same name as the class
They have no return type not even void
No return statement
The first line of a constructor must
either be a call on another constructor in the same class (using
this),
or a call on the superclass constructor (using super)
If the first line is neither of these, the compiler automatically
inserts a call to the parameter-less super class constructor
Call the constructor by preceding it with the new keyword
Person Constructor
class Person {
String name;
int age;
Person(String n, int a) {
name = n;
age = a;
}
// . . .
}
Now we can construct the previous example as follows:
Person person= new Person(“Chala", 22);
Types of constructors
Default constructor: this initializes objects based on
default values, takes no argument.
Parameterized constructor: these initialize objects based
on some parameter values.
Copy constructor: new objects are initialized based on
existing object of the same type.
20
/* Here, Box uses a constructor to initialize the
dimensions of a box.*/
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;
}
21
// 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);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
} }
22
When this program is run, it generates the following results:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
Parameterized Constructors
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;
}}
23
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
each object is initialized as specified in the parameters to its
constructor.
The this Keyword
can be used inside any method to refer to the current object.
is always a reference to the object on which the method was
invoked.
can use anywhere a reference to an object of the current class'
type is permitted.
consider the following version of Box( ):
// A redundant use of this.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
25
Instance Variable Hiding
when a local variable has the same name as an instance
variable, the local variable hides the instance variable.
this lets you refer directly to the object, you can use it to resolve any
name space collisions that might occur between instance variables
and local variables.
// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
26
Overloading Methods and Constructors
Overloading Methods
Two or more methods share the same name
overloaded methods must differ in the type and/or number of
their parameters. When this is the case, the methods are said to
be overloaded, and the process is referred to as method
overloading.
Method overloading is one of the ways that Java implements
polymorphism.
27
Here is a simple example that illustrates 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);
}
28
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;
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.2);
System.out.println("Result of ob.test (123.2): " +
result);
29
This program generates the following output:
No parameters
a: 10
a and b: 10 20
double a: 123.2
Result of ob.test(123.2): 15178.24
Method overloading supports polymorphism because it is one
way that Java implements the "one interface, multiple
methods" paradigm.
30
Overloading Constructors
/* 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;
height = h;
depth = d;
}
31
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
32
class OverloadCons {
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);
}} 33
The output produced by this program is shown here:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
Objects as Parameters
consider the following simple program:
// Objects may be passed to methods.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
34
// 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));
}
}
35
This program generates the following output:
ob1 == ob2: true
ob1 == ob3: false
One of the most common uses of object parameters involves
constructors.
Argument Passing
there are two ways that a computer language can pass an
argument to a subroutine.
The first way is call-by-value.
The second way an argument can be passed is call-by-
reference.
a reference to an argument (not the value of the argument) is
passed to the parameter.
changes made to the parameter will affect the argument used to
call the subroutine.
when you pass a simple type to a method, it is passed by value.
36
consider the following program:
// Simple types are passed by value.
class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}
}
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " + a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " + a + " " + b);
}}
37
The output from this program is shown here:
a and b before call: 15 20
a and b after call: 15 20
In call-by-value, the actual value of the argument is passed to the method. The method
receives a copy of the value stored in the variable, and any modifications made to the
parameter inside the method do not affect the original value.
Changes to the object inside the method do affect the object
used as an argument.
For example, consider the following program:
// Objects are passed by reference.
class Test {
int a, b; // pass an object
void meth(Test o) {
Test(int i, int j) { o.a *= 2;
a = i; o.b /= 2;
}
b = j; } }
38
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);
}
}
This program generates the following output:
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10
the fields are accessible for both main method and instance
method)
Sample output :
Enter Stud name:Abebe
Enter Stud Id no:0000
Enter Stud Sex:M
Student Information: Name : Abebe ID: 0000 sex:M
40
MyMath Example
public class MyMath {
public double PI = 3.14159;
public double square (double x) {
return x * x;
}
m.square(5));
System.out.println(“The second Object”);
MyMath n = new MyMath();
System.out.println(“value of PI is " + n.PI);
System.out.println(“square of 5 is " +
n.square(5));
}
}
The results of invoking square() method on instances m and
n are the same:
The First Object
value of PI is 3.14159
square of 5 is 25
The Second Object
value of PI is 3.14159
square of 5 is 25
43
Instance methods
associated with an object
use the instance variables of that object
the default
called by prefixing it with an object
E.g Circle c1 = new Circle()
c1.area();
Static Methods:
They can only call other static methods.
They must only access static data.
They cannot refer to this or super in any way.
Can’t access instance variables of any object
Calling static methods
Called from within the same class: Just write the static method name
E.g. double avgAtt = mean(attendance);
Called from outside the class: by prefixing it with a class name
E.g. Math.max(i, j)
44
MyMath with static
public class MyMath {
public static double PI = 3.14159;
public static double square (double x) {
return x * x;
}
Static blocks are useful for initializing static variables or performing one-
46
public static void main(String args[]){
System.out.println(“Before object creation ” +
y + " " + z);
StaticBlock s = new StaticBlock();
System.out.println(“After object creation ” + y
+ “ ”+ z + “ “ + s.x);
}
}
Here is the output of the program:
Inside Static Block
Before object creation 10 20
After object creation 40 40 30
47
What if the driver class is in a separate class?
class StaticBlock{
int x;
static int y, z;
StaticBlock(){
System.out.println("Inside Constructor");
x = y + z;
y = z = 40 ;
}
static{
y = 10;
z = 20 ;
System.out.println("Inside static block");
}
}
48
class MainTest{
public static void main(String args[]){
System.out.println("Before object
creation“+StaticBlock.y +“
”+StaticBlock.z);
StaticBlock s = new StaticBlock();
System.out.println("After object creation" +
StaticBlock.y + " "+ StaticBlock.z + " " + s.x);
}
}
Output:
Inside static block
Before object creation 10 20
Inside Constructor
After object creation40 40 30
49
static methods and variables can be used independently of any
object.
you need only specify the name of their class followed by the
dot operator.
The general form:
classname.method( )
A static variable can be accessed in the same way—by use of
the dot operator on the name of the class
50
Access Control(modifier)
Through encapsulation, you can control what parts of a
program can access the members of a class.
By controlling access, you can prevent misuse
How a member can be accessed is determined by the access
specifier that modifies its declaration
Some aspects of access control are related mostly to
inheritance or packages.
Java's access specifiers are: public, private, and protected
Java also defines a default access level.
protected applies only when inheritance is involved.
Public - member can be accessed by any other code in your
program
Private - member can only be accessed by other members of
its class. 51
When no access specifier is used, then by default the member
of a class is public within its own package, but cannot be
accessed outside of its package.
To understand the effects of public and private access,
consider the following program:
class Test {
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) { // set c's value
c = i;
}
int getc() { // get c's value
return c;
}
}
52
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;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " + ob.b
+""+
ob.getc());
}
53
}
The final keyword
We declared PI as
public static double PI = 3.14159;
but this does not prevent changing its value:
MyMath.PI = 999999999;
Use keyword final to denote a constant :
changed!
The keyword final can also be applied to methods,
to variables.
When final is applied to a method, it means that the method
55