OOP Chapter 2
OOP Chapter 2
1
Introduction
Java is a true object-oriented language and therefore the
underlying structure of all Java programs is classes.
A class is a template or prototype that defines a type of object.
Everything we wish to represent in a Java program must be
encapsulated in 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.
Methods: say what a class does
Introduction
An object is a software bundle that has State and
Behaviour.
An Object's state is stored in variables called fields. An
Object's behaviour is defined by its methods.
Example 1: Dogs (States: name, colour, breed, and “is
hungry?” and Behaviours: bark, run, and wag tail).
Example 2: Cars (States: colour, model, speed, direction
and Behaviours: accelerate, turn, change-gears)
Introduction
Introduction
Circle
centre
radius
circumference()
area()
The basic syntax for a class definition:
class ClassName [extends SuperClassName]
{
[fields declaration]
[methods declaration]
}
5
Introduction
Bare bone class – no fields, no methods
public class Circle {
// my circle class
}
Adding Fields
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle
}
The fields (data) are also called the instance variables.
6
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 immediately after
the declaration of data fields.
The structure of a method includes a method signature and a 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.
7
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
8
Adding Methods to Class Circle
9
Object
It is an instance of a class
Represents something with which we can interact in a program
Creating an object: It is a two step process
1. creating a reference variable
Syntax:
10
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)
11
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();
}
}
12
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);
}
}
13
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.
14
Person Example
class Person {
String name = “You”;
int age = 26;
void setName(String n) { name = n; }
String getName() { return name; }
}
Constructing Person Objects
Can we create a Person that has the name Tafera and the
age 22 from the moment it is created?
Answer: Yes!
Constructors
It is possible to initialize objects they are created by using
the dot (.) operator and with the help of methods. But it
would be simpler and more concise to initialize an object
when it is first created.
Java supports a special type of method, called a constructor,
that enables an object to initialize itself when it is created.
Constructors are special methods that are used to construct
an instance of a class.
A constructor initializes an object immediately upon
creation.
But object creation only doesn‟t call constructor rather it
will be called when the object is instantiated.
Call the constructor(s) preceding it with the new keyword.
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:
25
Garbage Collection
is the process of automatically finding memory blocks that are
no longer being used ("garbage")
when no references to an object exist, that object is assumed
to be no longer needed, and the memory occupied by the
object can be reclaimed.
Garbage collection only occurs sporadically (if at all) during
the execution of your program
E.g.
aCircleBefore
= newAssignment
Circle(); bCircle = new Circle() ;
After Assignment
bCircle = aCircle;
aCircle bCircle aCircle bCircle
26 P Q P Q
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
example
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
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.
31
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);
}}
32
The output from this program is shown here:
a and b before call: 15 20
a and b after call: 15 20
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;
Test(int i, int j) {
a = i;
b = j; }
// pass an object
void meth(Test o) {
o.a *= 2;
o.b /= 2; }
}
33
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
34
Exercise
35
Understanding static
When a member is declared static,
it can be accessed before any objects of its class are created,
and
Without reference to any object.
You can declare both methods and variables to be static.
When objects of its class are declared, no copy of a static
variable is made.
all instances of the class share the same static variable.
Two kind of methods
Instance Methods
Static Methods
36
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 a1 = new Circle()
A1.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)
37
MyMath with static
public class MyMath {
public static double PI = 3.14159;
public static double square (double x) {
return x * x;
}
39
Access Control
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.
40
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;
}
}
41
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());
}
}
42
What is encapsulation?
Hiding the data within the class
Making it available only through the methods
Each object protects and manages its own data. This is
called self-governing.
Methods
Data
43
10/07/22
Why encapsulation?
To hide the internal implementation details of your
class so they can be easily changed
To protect your class against accidental or willful
mistakes
In general encapsulation
separates the implementation details from the interface
44
10/07/22
Using Set and Get Methods
A class’s private fields can manipulate only by
methods of that class
How can we access those data outside?
Using set and get methods
Set methods
public method that sets private variables
Does not violate notion of private data
Change only the variables you want
Called mutator methods (change value)
Get methods
public method that displays private variables
Again, does not violate notion of private data
Only display information you want to display
Called accessor or query methods
45
10/07/22
With out Encapsulation
Class Person { class PersonTest{
String firstName; public static void
String lastName; main(String args[]){
int age; Person p1 = new Person();
Void display(){ p1.age = 20;
System.out.print(“welcome”); // p1.age = -21 possible
System.out.print(firstName); p1.lastName=”Dawit”;
System.out.print(lastName); p1.firstname = “Kassa”;
} p1.dispaly();
} }
}
46
10/07/22
With Encapsulation
Class Person {
public void setAge(int i){
Private String firstName;
Private String lastName; age = i;
Private int age; }
public String getfirsName(){ public setfirstName(String name){
return firstName; firstName = name;
}
public String getlastName(){
}
return lastName; public setlastName(String name){
} lastName = name;
public int getAge(){ }
If(i<=0) }
System.out.println(“wrong age”);
age = i;
}
47
10/07/22
class PersonTest{
public static void main(String args[]){
Person p1 = new Person();
p1.age = 20; // error b/c it is private
p1.setAge(20); // correct b/c setAge() is public
p1.setAage() = -21 // output : wrong age
p1.lastName=”Dawit”; // error b/c it is private
p1.setFirstName(“Dawit);
p1.setLastName = “Kassa”;
p1.dispaly();
}
}
48
10/07/22