You are on page 1of 32

Object-Oriented

Programming with Java


Computer Science Year II
Compiled by: Gebreigziabher A.

1
Objects & Classes
2
Objects
*Object-Oriented programming or OOP revolves around the concept of
objects as the basic elements of programs.
*These objects are characterized by their properties (or attributes) and
behaviors.
*The objects in the physical world can easily be modelled as software
objects using the properties as data and the behaviors as methods.
*Each object is composed of a set of data (properties/attributes) which are
variables describing the essential characteristics of the object, and a set of
methods (behaviors) that describes how an object behaves-performing
some task.
*Thus, an object is a software bundle of variables and related methods. The
variables and methods in a Java object are formally known as instance
variables and instance methods to distinguish them from class variables
3
and class methods.
*Objects are instances of a class.
*An object is a building block which contains variables and methods.
*An object is a software bundle of related state and behavior.
Software objects are used to model the real-world objects in
everyday life.
*Objects interact with each other by passing messages.
*Methods and variables that constitute a class are called members of
the class.
*The data members or variables, defined with in a class are called
instance variables.

4
*A Class is a template, a prototype or a blueprint of an object.
*A class is a programmer defined type that serves as a blueprint for
instances of the class.
*It consists of two types of members which are called fields
(properties or attributes) and methods. Fields specify the data
types defined by the class, while methods specify the operations.
*Classes provide the benefit of reusability. Software programmers
can use a class over and over again to create many objects.
*A class is a template/ blueprint/prototype that defines the form of
an object.
*A class is a collection of data and methods that operate on that
data.
*A Class is a blueprint that defines the states and the behaviors
common to all objects of a certain5 kind.
*A class is created by using the keyword class.
General Form:

class ClassName { Example:


// declare instance variables
type var1; // Class declaration with one method.
type var2;
// ... public class Course
type varN;
{
// declare methods
type method1(parameters) { // display a welcome message to the Course user
// body of method
} public void displayMessage() {
type method2(parameters) { System.out.println( “OOP with Java!”);
// body of method
} } // end method displayMessage
// ...
type methodN(parameters) { } // end class Course
// body of method
} 6
}
* Objects are created with new keyword.
* The new operator dynamically allocates ( that is, allocates at run time) memory
for an object and returns a reference to it. This reference is, more or less, the
address in memory of the object allocated by new. This reference is then
stored in the variable . Thus , in Java, all class objects must be dynamically
allocated.
* General Form
ClassName obj = new ClassName( ); // Allocate class object
obj.MethodName(); //Calling/invoking the Method
* Alternatively,
ClassName obj ; /*declare reference to object contains null value, which indicates that it
does not yet point to an actual object*/
obj = new ClassName( ); // Allocate class object
Example:
Course c = new Course(); //Creating object called c for class Course
7
c.displayMessage(); //Calling the displayMessage() method
class Person {
String name = “Abebe”; // initializes name
int age = 26; // initializes age
void setName(String n) { name = n; } //store name
String getName() { return name; } // retrieve name
void setAge(int a) { age = a; } //store age
int getAge() { return age; } // retrieve age
}
To create an instance (P )of the Person class with a name of “Henok" and an age of 22
Person P= new Person();
P.setName(“Henok");
P.setAge(22);

8
public class Addition {
int x,y;
public double add() {
return x+y;
}
public class AdditionTest {
public static void main(String args[]) {
Addition ad = new Addtion();
// Assign values to ad’s instance variables
ad.x=5;
ad.y=7;
sum= ad.add();
System.out.println(“The Sum of ”+ad.x+” and ”+ad.y+” is: ”+sum);
}
}
* Object reference variables act differently than you expect when an assignment
take place. For example:
Course c1 = new Course( );
Course c2 = c1;
* c1 and c2 will both refer to the same object. The assignment of c1 and c2 did not
allocate any memory or copy any part of the original object . It simply makes c2
refer to the same object as does c1.
* When an instance is assigned to a variable, that variable is said to hold a
reference or point to that object
Person g = new Person(“Abebe", 26);
Person h = new Person("Abebe", 26);
* g and h hold references to two different objects that happen to have identical state
* The object creation statement has three parts.
Course c = new Course();
10
Declaration Instantiation Initialization
* Declare variables of int type as: -
int a; //a is a variable which refers to any type of int data.
* Declaration: Associates a variable name with an object type.
* Classes in java are also types so declare class type variable as: -
Course c; //c is a variable which refers to any type of Course.[Used to refer
Course object]
* Declaring a object variable (Course c; )do not create any object until assigned
with a new keyword.

2. Instantiation
* The new operator instantiates a class by allocating a memory for a new object.
The new operator returns a reference to the object it created and this reference
is assigned to the appropriate variable.
Course c = new Course(); //Create object called c & reserve/allocate memory to that object
* Instantiating a class means creating an object/Instance of a class.
11
* The object is always initialized by calling a constructor.
* A constructor is a special method which has a same name as class and used to
initialize the variables of that object.
* Course class object is initialized by calling the constructor of Course class:
Course( );

public class Course {


// method to retrieve the course name
private String courseName;
public String getCourseName() {
/*Constructor initializes courseName
return courseName;
with String supplied as argument*/
} // end method getCourseName
public Course(String cname ) { // display a welcome message to the Course user
courseName = cname; // initializes public void displayMessage() {
courseName
// this statement calls getCourseName to get
} // end constructor
// name of the course this Course represents
} // end class Course
System.out.println( "Welcome to the”+
// method to set the course name
getCourseName() );
public void setCourseName( String
} // end method displayMessage
cname ) {
} // end class Course
courseName = cname;//store the course
name
12
} // end method setCourseName
// Course constructor used to specify the course name at the time each Course object
is created.
public class CourseTest {
public static void main( String args[] ) { // main method begins program execution
// Create Course object
Course c1 = new Course(“Comp321 Object Oriented Programming" );
Course c2 = new Course(“Comp222 Fundamentals of Programming II" );
// display initial value of courseName for each Course
System.out.println( “Course I Course Name ", c1.getCourseName() );
System.out.println " Course II Course Name ", c2.getCourseName() );
} // end main
} // end class CourseTest 13
* Object variables are instance of a class that are created from the class.
* Example:
Student stud; //declaration of object variable of type Student (The object stud is now null)
Student stud = new Student(); //Create stud object from Student

public class Student {


String studID;
char grade;
public Student(String id, char g) { //Constructor
studID = id;
grade = g;
}
public void displayInfo() { //Method for displaying student info
System.out.println(“Student ID=”+studID+” Grade=”+grade);
}
public class StudentTest {
public static void main(String args[]) {
String studID = “ETR/400/04”; char grade = “B”; //Initialize
Student stud = new Student(StudID, grade); //Create object
stud.displayInfo(); //Call/Invoke the method
14
}
}
* A Constructor is a special method in java class that is used to initialize a new object
variables. Constructors have no return type even void.
* A constructor has the same name as the class. For example the constructor of
Course class is Course( );
* Constructors cannot return any value not even void.
* If we are not providing any constructor for a class than default (no parameter)
constructor is automatically provided by the runtime system.
* The constructor can be private, public or protected.
class Person {
String name;
int age;
Person(String n, int a) { //Constructor to initialize instance variables name & age
name = n;
age = a;
}
// . . .
}
Person p= new Person(“Abebe", 22); //Create instance of a class
15
* When a constructor is not provided in a class, it implicitly has a constructor with no
arguments and an empty body. Generally speaking, every class has a constructor.
class Student {
// Leaving out the constructor is the same as . . .
Student() { }
}
The this Keyword
* The this keyword special reference value used inside any instance method to refer
to the current object . The value this refers to the object which the current method
has been called on . The this keyword can be used where a reference to an object
of the current class type is required .
class Person {
String name;
int age;
Person(String name, int age) { //Constructor to initialize instance variables name & age
this.name = name;
this.age = age;
}}
Now Construct a Person like: Person P = new 16
Person(“Abebe”, 22);
* The keyword this is used to reference a field/method from inside the same class.
* Within an instance method or a constructor, this is a reference to the current
object - the object whose method or constructor is being called. You can refer to
any member of the current object from within an instance method or a
constructor by using the this keyword or without using the this keyword
Example,
public class Rectangle {
int width = 5;
int height = 4;
public void Display(){
System.out.println("Width and height are: " + this.width + ", " +this.height);
}
}

* To invoke another constructor of current class inside constructor:


int x,y;
Addition(int x, int y) { this.x=x; this.y=y; }
Addition() {
this(4, 5); // invoke the current class constructor that takes two int arguments.
} 17
public class Point {
public class GradePtAvg { int x,y;
String studID;
void init (int x , int y) {
double gpa;
this.x = x;
public GradePtAvg(String studID, double gpa) {
this.studID = studID; this.y = y;
this.gpa = gpa; }
} void display ( )
String getstudID() { return studID; } {
double getgpa() { return gpa ; }
System.out.println (" x = "+ x);
void setgpa(double g) { gpa = g; }
System.out.println (" y = "+ y );
}
public class GPATest { }
public static void main(String[] args) { }
GradePtAvg gp = new GradePtAvg("123", 3.75); public class PointTest {
System.out.println(gp.getstudID()); //123 public static void main(String[] args) {
System.out.println(gp.getgpa()); //3.75 // TODO code application logic here
gp.setstudID(“124”); //set studID to 124
Point P = new Point() ;
gp.setgpa(3.5); //set gpa to 3.5
System.out.println(gp. getstudID());//display 124 P.init(4,3);
System.out.println(gp.getgpa()); //display 3.5 P.display() ;
} }
} } Output x=4
18
y=3
* Access modifiers define various levels of access between class members and the
outside world (other objects).
* They allow us to define the encapsulation characteristics of an object.
* There are four access modifiers in java:
1. private – Most restrictive, accessible only by its own class
2.protected – Accessible by its own class & derived/sub/child class
3.public - Accessible to anyone, both inside and outside the class(Have global visibility )
4.default - Accessible to only classes in the same package. No actual keyword for declaring
default access modifier, applied by default in the absence of any access modifier.

Access Modifier Accessible from Accessible from Accessible from


own class derived class objects(Outside class)
public Yes Yes Yes
protected Yes Yes No
private Yes No No
19
* Methods are functions that operate on instances of classes in which they are
defined. Objects can communicate with each other using methods and can call
methods in other classes. Just as there are class and instance variables, there are
class and instance methods . Instance methods apply and operate on an instance of
the class while class methods operate on the class .
* A method is a separate piece of code that can be called by a main program or any
other method to perform some specific function.
* Methods are subroutines that manipulate the data defined by the class and, in
many cases, provide access to that data.
* A method is the object-oriented term for a procedure or a function that performs
some task.
* Why do we need to create methods? Why don't we just place all the code inside
one big method? The heart of effective problem solving is in problem
decomposition. We can do this in Java by creating methods to solve a specific part
of the problem. Taking a problem and breaking it into small, manageable pieces is
critical to writing large programs.

20
* The type, name and arguments together is referred to as the signature of the method
* Method definition has four parts . They are , name of the method, type of object or
primitive type the method returns, a list of parameters and body of the method.
General form:

Return type Name Arguments

Returntype methodName(type1 arg1 , type2 arg2 ) {


// Body of the methods Body
}
Example:
double computeArea(int base, int height) {
double A;
return A = (base*height)/2;
}

21
*A method has 4 parts: the return type, the name, the arguments,
and the body:
type name arguments

double sqrt(double num) {


body // a set of operations that compute
// the square root of a number
}

int isPrime(int num) {


//Block of code that checks whether a number is prime or not
}
int isPerfect(int num) {
//Block of code that checks whether a number is perfect or not
} 22
* The methods are accessed using the dot notation .
General form:
obj.methodName ( param1, param2 );
Example:
public class Area {
int len = 10;
int wid = 10;
public void calculateArea( ) {
int area = len * wid ;
System .out .println( “ The area of rectangle is “ + area + “ sq. cms “);
}}
public class AreaTest {
public static void main ( String args [ ] ) {
Area a= new Area ( ) ; //Creating object a for class Area
a.calculateArea ( ) ; //Calling/Invoking the Method
}
} 23
* Parameters refers to the list of variables in a method declaration.
double Area(double height, double width) // 2 parameters height & width
double Area(double radius) //1 parameter radius
double findSquareRoot(double num ) // 1 parameter num
double isPerfect(int num ) //1 parameter num
int isEven(int num ) // 1 parameter num

Method Arguments[Passing Arguments to


Methods]
* Arguments are the actual values that are passed in when the method is invoked.
Example:
int n=6;
Perfect P = new Perfect(n) ; // n is actual value called argument passed to method
P.isPerfect(); //Invoke/Call the Method isPerfect()
int x=3, y=5;
Addition A = new Addition(x, y) ; // x & y are actual value called argument passed to method
A. Add(); //Invoke/Call the Method Add()
int findSquare(int x) { return x*x; }
Square s=new Square ( ) ; //Create instance24a class called s
s.findSquare( 15 ) ; //15 is argument passed to method findSquare()
* The body of a method is a block specified by curly brackets. The body defines the
actions of the method.
int isEven(int num ) {
if(num%2==0) {
System.out.println(“The Number is Even.”);
}
Method body
else {
System.out.println(“The Number is Even.”);
}
}

The main Method- A Special Method


The main method is where a Java program execution always starts.
public static void main(String[] args) {
//. . .
} 25
* The return type of a method may be any data type.
* The type of a method designates the data type of the output it produces.
* Methods can also return nothing in which case they are declared void.
* Example:
double divide(double a, double b) {
double answer;
answer = a / b;
return answer;
}

void Methods
A method of type void has a return statement without any specified value. i.e. return;
Any method declared void doesn't return a value.
It’s used to branch out of a control flow block and exit the method. return;
26
public void dispalyMsg() { System.out.println(“Hello Computer Science”); }
*The return statement is used in a method to output the result of
the methods computation.
*It has the form: return expression_value;
*The type of the expression_value must be the same as the
type of the method:

double sqrt(double num){


double answer=Math.sqrt(num);
//Compute the square root of num and store the value into the variable answer
return answer;
}
*A method exits immediately after it executes the return statement.
*Therefore, the return statement is usually the last statement in a
method. 27
* Recursive Method is procedure or a function that calls it
self.
import java.util.*;
public class Factorial {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a Number: ");
int num = s.nextInt(); //Obtain integer input
System.out.println(fact(num)); //Calling static method fact()
}
public static int fact(int n) {
if (n <= 1) { return 1; }
else { return n*fact(n-1); }
} 28
}
.
Method Description Example
abs( x ) absolute value of x (this method also has float, abs( 23.7 ) is 23.7
int and long versions) abs( 0.0 ) is 0.0
abs( -23.7 ) is 23.7
ceil( x ) rounds x to the smallest integer not less than x ceil( 9.2 ) is 10.0
ceil( -9.8 ) is -9.0
cos( x ) trigonometric cosine of x (x is in radians) cos( 0.0 ) is 1.0
exp( x ) exponential method ex exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
floor( x ) rounds x to the largest integer not greater than floor( 9.2 ) is 9.0
x floor( -9.8 ) is -10.0
log( x ) natural logarithm of x (base e) log( Math.E ) is 1.0
log( Math.E * Math.E ) is 2.0
max( x, y ) larger value of x and y (this method also has max( 2.3, 12.7 ) is 12.7
float, int and long versions) max( -2.3, -12.7 ) is -2.3
min( x, y ) smaller value of x and y (this method also has min( 2.3, 12.7 ) is 2.3
float, int and long versions) min( -2.3, -12.7 ) is -12.7
pow( x, y ) x raised to the power y (xy) pow( 2.0, 7.0 ) is 128.0
pow( 9.0, 0.5 ) is 3.0
sin( x ) trigonometric sine of x (x is in radians) sin( 0.0 ) is 0.0
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent of x (x is in radians) tan( 0.0 ) is 0.0

29
* Variables are areas allocated by the computer memory to hold data.
Class variable Instance variable
Class variable is declared by using Instance variable is declared without
static keyword. static keyword.
static int a = 4; int a = 4;
All objects share the single copy of All objects have their own copy of
static variable. instance variable.
Belong to the whole class-static
member variable.
Static variable does not depend on Instance variable depends on the
the single object because it belongs object for which it is available.
to a class.
Static variable can be accessed without Instance variable cannot be accessed
creating an object, by using class name. without creating an object.
ClassName.variable ObjectName.variable
30
s
Static Method Instance Method
Static methods are declared by using instance methods are declared without
static keyword. static keyword.
static type method( ); type method( );
All objects share the single copy of All objects have their own copy of
static method. instance method.
Static method does not depend on the Instance method depends on the object for
single object because it belongs to a class. which it is available.

Static method can be invoked without Instance method cannot be invoked


creating an object, by using class name. without creating an object.
ClassName.method( ); ObjectName.method( );

Static methods cannot call non-static Non-static methods can call static
methods. methods.
Static methods cannot access not- Non-static methods can access static
static variables. variables.
31
Static methods cannot refer to this or Instance methods can refer to this and
super. super.
 When to declare variable as static? When value of the variable remains the same for all class
instance created & being used in every instance. They’ll be loaded when a class loads.
 Static tells compiler there’s exactly one copy of this variable in existence, no matter how
many times class has been instantiated.
 Static method or variable is not attached with specific object, but to class as a whole. They are
allocated when the class is loaded.
Static methods are declared when the behavior of method doesn’t change for each object created
[i.e. behaviors of method remain the same for all instances created.]
// Demonstrate static variables, methods and blocks.
class UseStatic {
static int a = 3;
static int b;
Output
static void meth ( int x ) {
Static block Initialized
System.out.println ( “ x = “ + x );
x = 42
System.out.println ( “ a = “ + a );
a=3
System.out.println ( “ b = “ + b );
b = 12
System.out.println ( “ Static block initialized . “ );
b=a*4;
}
public static void main ( String args [ ] ) { meth ( 42 ); }
} 32

You might also like