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

OOP Lecture 04

Uploaded by

joashtekeleza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

OOP Lecture 04

Uploaded by

joashtekeleza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 65

Object Oriented

Programming
Methods, Objects,
Classes, Encapsulation
and, Constructors

1
OOP Concepts

Object

Class

Encapsulation

Inheritance

Polymorphism

Abstraction
2
Methods
A piece of code which execute some logic
 Performs some tasks and returns results or control

 Defines behavior of objects

 Used for communication between objects

 Allow you to modularize a program by separating

its tasks into self contained units


 Statements in the method bodies are written only

once, reused from several parts of program, are


hidden from other methods.
 Allow divide-and-conquer
3
 Allow software reusability
Methods
Syntax :
Access modifiers returnType methodName(parameterList)
{
//Method Body
}

4
Methods
 e.g. :-
 public int getNumber();
 private void setData(String name, int age)
 protected DefinedClass getDefinedClass()

 Return Types
 void
 Primitive types
 Object Type
 Array Type
5
Methods-Parameters and
Arguments
 Parameter list is a comma separated list of variable
declarations within the parentheses of a method
 Each parameter identifies the parameter’s type and a

name by which the parameter can be referenced


 A parameter may be referenced anywhere within the

method
 Arguments are data values passed to parameters

during a method call


 Method arguments may be constants, variables or

expressions.
6
Methods-Parameters and
Arguments
//Declaration of a method with parameters

int myMethod(int x, double y)


{
//code
}

//invoking a method and passing arguments


objectName.myMethod(5, 4.9);

7
Methods
 Methods are used by invoking them with
respect to an object reference
Syntax :
objectName.methodName(argument List)
e.g. :-
String treeName =
tree.getName( value );

8
Methods-call
 There are three ways to call a method:
 Using a method name by itself to call another
method of the same class.
 Using a variable that contains a reference to an
object, followed by a dot (.) and the method name
to call a method of the referenced object.
 Using the class name and a dot (.) to call a static
method of a class.
A method can either return results(value) or a
control to the collar
9
Methods-call
 Two ways to pass arguments in method calls in many
programming languages are pass-by-value and pass-
by-reference (also called call by-value and call-by-
reference).
 When an argument is passed by value, a copy of the

argument’s value is passed to the called method.


 The called method works exclusively with the copy.

 When an argument is passed by reference, the called

method can access the argument’s value in the caller


directly and modify that data, if necessary.
 In java all arguments are passed by value-copy of

primitive value or copy of reference to object. 10


Methods-array as parameters
and arguments
 Array
 double hourlyTemperatures[] = new double[ 24 ];
 Specify an array parameter.
 void modifyArray( int b[] )
 Inmethod call, provide the name of array without
angle brackets as an argument.
 modifyArray( hourlyTemperatures );

11
Methods-array as parameters
and arguments
public class PassArray{
public static void main( String args[] ){
int array[] = { 1, 2, 3, 4, 5 };
System.out.println("Effects of passing reference to entire array:\n" + "The values of the original array are:" );
for ( int value : array ) // output original array elements
System.out.printf( " %d", value );
modifyArray( array ); // pass array reference
System.out.println( "\n\nThe values of the modified array are:" );
for ( int value : array ) // output modified array elements
System.out.printf( " %d", value );
System.out.printf("\n\nEffects of passing array element value:\n" + "array[3] before modifyElement: %d\n",
array[ 3 ] );
modifyElement( array[ 3 ] ); // attempt to modify array[ 3 ]
System.out.printf("array[3] after modifyElement: %d\n", array[ 3 ] );
} // end main
public static void modifyArray( int array2[] ){ // multiply each element of an array by 2
for ( int counter = 0; counter < array2.length; counter++ )
array2[ counter ] *= 2;}
public static void modifyElement( int element ){ // multiply argument by 2
12
element *= 2;
System.out.printf("Value of element in modifyElement: %d\n", element );}}
Methods-static
 Static methods apply to the class as a whole rather than an
instance of the class
 Static methods can be invoked using the same notation as non-
static methods
 However it is more appropriate to invoke static methods using
the class name rather than a variable name
 To declare a method as static, place the keyword static before
the return type in the method’s declaration.
 Note that a static method can call only other static methods of
the same class directly (i.e., using the method name by itself)
and can manipulate only static fields in the same class directly.
 Java does not allow a static method to access non-static
members of the same class directly.
 To access the class’s non-static members, a static method 13
must use a reference to an object of the class.
Methods
e.g no parameters, no return type
Public class MyClass
{
public static void main(String args[])
{
myMethod();
}

public static void myMethod()


{
System.out.println("Hallow Java");
} 14
Methods
e.g Parameters
Public class MyClass{
public static void main(String args[]){
myMethod("said");
add(23,56);
add(45,89);
add(56,577);
add(34,67);
}
public static void myMethod(String name){
System.out.println("hellow " + name);
}
public static void add(inta, intb){
System.out.println(a + b);
}
15
}
Methods
 e.g Returning a value
public class MyClass{
public static void main(String args[]){
int sum = add(23,56);
System.out.println(sum);
}

public static void myMethod(String name){


System.out.println("hellow " + name);
}

public static int add(inta, intb){


return(a + b);
}
}
16
Method Overloading
 Several methods with the same name declared in
the same class but perform different logic or tasks
 These methods have different signature, differ in

type of parameter, number of parameters and


order of the parameters.
 Return type may be different or the same

 The compiler distinguishes overloaded methods by

their signature—a combination of the method’s


name and the number, types and order of its
parameters.
17
Method Overloading
 e.g
public class MyClass{
public static void main(String args[]){
System.out.println(Add(1,36));
System.out.println(Add(5.656,40.66));
System.out.println(Add("Hellow ","World"));
}
public static int Add(int a, int b){
return (a + b);
}
public static double Add(double a, double b){
return ( a+ b);
}
public static String Add(String a, String b){
return (a + b);
}
18
}
What is an Object?
 In real world, object is an entity that have state and behavior.
 e.g. chair, bike, marker, pen, table, car, phone etc

 State(variables, attribute, field): represents data (value) of an


object
 State change time to time and Methos are responsible for
change of state
 Behavior: represents the behavior (functionality) of an object
such as deposit, withdraw etc.
 e.g. Your Mobile phone
 State – Make, Model, Color

 Behavior – Receiving, Sending

 An object can be physical or logical (tangible and intangible).


 The example of intangible object is banking system.
19
What is an Object?
 An Object in Software is a bundle of variables (state)
and related methods (operations).
 Object is an instance of a class. Class is a template or

blueprint from which objects are created. So object is


the instance(result) of a class.
 Objects have identities

 Object identity is typically implemented via a unique

ID.
 The value of the ID is not visible to the external

user.
 But,it is used internally by the JVM to identify each

object uniquely. 20
What is an Object?

21
What is an Object?

22
What is an Object?

23
What is a Class?
A class is a group of objects that has common
properties.
 It is a template or blueprint from which objects are

created.
 It is a blueprint that defines the variables and

methods common to all objects of a certain kind


 A data type/structure in which you can define some

member variable and member methods


 Eg. ‘Your Mobile Phone’ is one Object belonging to

the Class, Phone


 An Object holds values for the Variables defined in
24

the class (e.g. Make = Nokia)


What is a Class?
A class in java can contain:
 data member

 method

 constructor

 block

 class and interface

25
Class Vs Object

 NumberOfGears is called a Class Variable and holds


the same value for all Objects of the Class
Cadence is the speed at which you turn the Cranks, 26
measured in revolutions per minute(rpm)
Class vs Object
 Classis the logical entity only whereas
Object is the physical as well as logical entity.
 Class is a template or blueprint from
which objects are created whereas Object
is an instance of a class(result of a class).

27
Syntax for declaring/defining a
class and Creating an object
//class definition/declaration
public class <className>
{
data member;
method;
}

//object creation
<className> ob = new <className> (); 28
Class and Object
 Program creates a class Student1 that have two data members
regNum and name. Creates the object of the Student1 class by
new keyword and prints the objects value.
 public class Student1{
int regNum; //data member (also instance variable)
String name; //data member(also instance variable)
public static void main(String[] args){
Student1 s1 = new Student1(); //creating an object of Student
System.out.println(s1. regNum);
System.out.println(s1.name);}}
 The new keyword is used to allocate memory at runtime
 A variable that is created inside the class but outside the
method, is known as instance variable. Instance variable
doesn't get memory at compile time. It gets memory at runtime
when object(instance) is created. That is why, it is known29 as
instance variable.
Encapsulation
 Enclose data inside an object
 Cannot be accessed directly from outside

 Provides data security

30
Encapsulation

Class
31
Encapsulation

32
Constructors
A Constructor is a special method
used to construct an object (instance)
from a class.
 Used for the initialization of the object.

 If not specified, the default constructor

is used.
 Class can have more than one

constructor 33
Constructors
 Each class you declare can provide a constructor that
can be used to initialize an object of a class when the
object is created
 constructor call is indicated by the class name

followed by parentheses
 the constructor must have the same name as the

class.
 Keyword new calls the class’s constructor to perform

the initialization.
 By default, the compiler provides a default

constructor with no parameters in any class that


does not explicitly include a constructor 34
Constructors
 If class does not declare any constructor, a compiler creates
default constructor to initialize objects to their default values
 If a class declares constructor, compiler will not create default
constructor. In this case to specify default initialization for object
of your class you must declare a no-argument constructor
 Default constructors and no-argument constructors are invoked
with empty parentheses.
 If a class has constructors, but none of the public constructors
are no-argument constructors, and a program attempts to call a
no-argument constructor to initialize an object of the class, a
compilation error occurs.
 A constructor can be called with no arguments only if the class
does not have any constructors (in which case the default
constructor is called) or if the class has a public no-argument 35

constructor.
Constructors
public class Cube {
int length;
int breadth;
int height;
Cube(){
length = 10;
breadth = 20;
height = 30;
}
public int getCubeVolume(){
return (length * breadth * height);
}
}
//client class
Public class MyClass{
Public static void main(String args[]{
Cube cube1 = new Cube(); 36

System.out.println(cube1.getCubeVolume());}}
Constructors
publicclass Cube {
int length;
int breadth;
int height;
Public int getCubeVolume(){
return (length * breadth * height);
}
Cube(){
length = 10;
breadth = 20;
height = 30;
}
Cube(intl, intb, inth){
length = l;
breadth = b;
height = h; }}
//client class
Public class MyClass{
publicstaticvoid main(String args[]){
Cube cube1 = new Cube();
System.out.println(cube1.getCubeVolume());
Cube cube2 = new Cube(20,20,20); 37

System.out.println(cube2.getCubeVolume()); }}
Constructors
public class GradeBook{ public class GradeBookTest
private String courseName; {
public GradeBook( String name ) { public static void main( String args[] )
courseName = name; {
} GradeBook gradeBook1 = new
public void setCourseName( String GradeBook("CS101 Introduction to
name ) { Java Programming" );
GradeBook gradeBook2 = new
courseName = name;
GradeBook("CS102 Data Structures
} in Java" );
public String getCourseName() { System.out.printf( "gradeBook1
return courseName; course name is: %s\n",
} gradeBook1.getCourseName() );
public void displayMessage() { System.out.printf( "gradeBook2
course name is: %s\n",
System.out.printf( "Welcome to the
gradeBook2.getCourseName() );
grade book for\n%s!\n",
getCourseName() ); } } } 38

}
Constructors
import java.util.Scanner;
public class Account{ public class AccountTest{
private double balance; public static void main( String args[] ) {
Account account1 = new Account( 50.00 );
public Account(double initialBalance){ Account account2 = new Account( -7.53 );
System.out.printf( "account1 balance:$%. 2f\n",
if ( initialBalance > 0.0 ) account1.getBalance() );
balance = initialBalance; System.out.printf( "account2 balance:$%. 2f\n\n",
account2.getBalance() );
} Scanner input = new Scanner( System.in );
double depositAmount;
public void credit(double amount) { System.out.print( "Enter deposit amount for account1: " );
depositAmount = input.nextDouble();
balance = balance + amount; System.out.printf( "\nadding%.2f to account1 balance\n\n",
} depositAmount );
account1.credit( depositAmount );
public double getBalance() System.out.printf( "account1 balance:account1.getBalance() );
System.out.printf( "account2 balance:$%.2f\n\n",
{ account2.getBalance() );
System.out.print( "Enter deposit amount for account2: " );
return balance; depositAmount = input.nextDouble();
} System.out.printf( "\nadding %.2f to account2 balance\n\n",
depositAmount );
} account2.credit( depositAmount );
System.out.printf( "account1 balance:$%.2f\n",
account1.getBalance() ); System.out.printf( "account2 balance:$
39
%.2f\n", account2.getBalance() );
}}
Defining a Class

40
Objects and Classes
//class
public class Grade{
public void displayMessage(){
System.out.println( "Welcome to the Grade!" );
}
}

//class with main


public class GradeTest{
public static void main( String args[] ){
Grade myGrade = new Grade();
myGrade.displayMessage();
} 41
Objects and Classes
 When each object of a class maintains its own copy of an
attribute, the field that represents the attribute is also known as
an instance variable—each object (instance) of the class has a
separate instance of the variable in memory.

42
Objects and Classes
public class GradeBook{ import java.util.Scanner;
private String courseName; public class GradeBookTest{
public static void main( String args[] ){
public void
Scanner t=new Scanner( System.in );
setCourseName( String
GradeBook myGradeBook = new
name ){ GradeBook();
courseName = name; System.out.printf( "Initial course name
} is: %s\n\n",
myGradeBook.getCourseName());
public String getCourseName(){ System.out.println( "Please enter the
return courseName; course name:" );
} String theName = input.nextLine();
myGradeBook.setCourseName( theN
public void displayMessage(){
ame );
System.out.printf( "Welcome to System.out.println();
the grade book for\n%s!\n", myGradeBook.displayMessage();
getCourseName());}} }}
43
Objects and Classes
//class
public class GradeBook{
public void displayMessage( ){
System.out.printf( "Welcome to the grade book for\n%s!\n",
courseName ); } }

//class with main


import java.util.Scanner;
public class GradeBookTest{
public static void main( String args[] ){
Scanner input = new Scanner( System.in );
GradeBook myGradeBook = new GradeBook();
System.out.println( "Please enter the course name:" );
String nameOfCourse = input.nextLine(); 44
Some Standards
 Class Names Start with a Uppercase and be a noun.
 String, Button etc

 Variable Names Start with a Lowercase


 myVariable

 Method Names start with a Lowercase and be a verb


 print(), display()

 Interface name start with uppercase and be an adjective


 Runable, remote etc

 Package name should be in lowercase letters


 lang, util etc

 Constants name should be in uppercase


 RED, PIE etc

 Always give meaningful names


 Use Indentation where necessary 45
Access Modifiers
 The access modifiers public, private and protected
control access to a class’s variables and methods.
 Public
 Variables or methods declared with access modifier public are
accessible to methods of other classes (class’s client) in which they
are not declared.
 Public class members are directly accessible outside the class.
 Private:
 Variables or methods declared with access modifier private are
accessible only to methods of the class in which they are declared.
 Private class members are not directly accessible outside the class.
 Declaring instance variables with access modifier private is known as
data hiding.
 Protected
 An intermediate access modifier between private and public 46
Access Modifiers

Modifier Class Package Subclass World

Public Y Y Y Y

Protected Y Y Y N

No modifier Y Y N N

Private Y N N N

47
this reference
 Allow object to access reference to itself
 When a non-static method is called for a

particular object, the method’s body


implicitly uses keyword this to refer to the
object’s instance variables and other
methods.

48
this reference
public class A{
public static void main(String[] args){
A t = new A(15, 30, 19);
System.out.println(t.B());
}}
class B{
private int x;
private int y;
private int z;
public B(int x, int y, int z){
this.x = x;
this.y = y;
this.z = z;
49

}}
Scope
 The scope of a declaration is the portion of the program
that can refer to the declared entity by its name.
 The basic scope rules are as follows:
 The scope of a parameter declaration is the body of the method
in which the declaration appears.
 The scope of a local-variable declaration is from the point at
which the declaration appears to the end of that block.
 The scope of a local-variable declaration that appears in the
initialization section of a for statement’s header is the body of
the for statement and the other expressions in the header.
 The scope of a method or field of a class is the entire body of
the class. This enables non-static methods of a class to use the
class’s fields and other methods.
 If a local variable or parameter in a method has the same name
50
as a field, the field is “hidden” until the block terminates
Scope
// Scope class demonstrates field and local variable scopes.
public class Scope{ // Application to test class Scope.
// field that is accessible to all methods of this class
private int x = 1; public class ScopeTest
// method begin creates and initializes local variable x
// and calls methods useLocalVariable and useField {
public void begin(){
int x = 5; // method's local variable x shadows field x // application starting point
System.out.printf( "local x in method begin is %d\n", x );
useLocalVariable(); // useLocalVariable has local x public static void main( String
useField(); // useField uses class Scope's field x
useLocalVariable(); // useLocalVariable reinitializes local x
args[] )
useField(); // class Scope's field x retains its value
System.out.printf( "\nlocal x in method begin is %d\n", x );
{
} // end method begin
// create and initialize local variable x during each call
Scope testScope = new Scope();
public void useLocalVariable()
{
testScope.begin();
int x = 25; // initialized each time useLocalVariable is called
System.out.printf("\nlocal x on entering method useLocalVariable is %d\n", x );
} // end main
++x; // modifies this method's local variable x
System.out.printf("local x before exiting method useLocalVariable is %d\n", x );
} // end class ScopeTest
} // end method useLocalVariable
// modify class Scope's field x during each call
public void useField() {
System.out.printf("\nfield x on entering method useField is %d\n", x );
x *= 10; // modifies class Scope's field x
System.out.printf("field x before exiting method useField is %d\n", x );
} // end method useField
} // end class Scope
51
Variable-length argument lists
 With variable-length argument lists, you can create
methods that receive an unspecified number of
arguments
 An argument type followed by an ellipsis (...) in a
method’s parameter list indicates that the method
receives a variable number of arguments of that
particular type.
 This use of the ellipsis can occur only once in a
parameter list, and the ellipsis, together with its type,
must be placed at the end of the parameter list.

52
Variable-length argument lists
public class VarargsTest{
public static double average(double... numbers){
double total = 0.0; // initialize total
for ( double d : numbers )
total += d;
return total /numbers.length;}
public static void main( String args[] ){
double d1 = 10.0;
double d2 = 20.0;
double d3 = 30.0;
double d4 = 40.0;
System.out.printf( "d1 = %.1f\nd2 = %.1f\nd3 = %.1f\nd4 = %.1f\n\n", d1, d2, d3,
d4 );
System.out.printf( "Average of d1 and d2 is %.1f\n", average( d1, d2));
System.out.printf( "Average of d1, d2 and d3 is %.1f\n", average( d1, d2, d3 ));
System.out.printf( "Average of d1, d2, d3 and d4 is %.1f\n", average( d1, d2, d3,53
d4 ));}}
Command-line arguments
 On many systems it is possible to pass arguments from the
command line (these are known as command-line arguments)
to an application by including a parameter of type String[] (i.e.,
an array of Strings) in the parameter list of main
 By convention, this parameter is named args.
 When an application is executed using the java command,
Java passes the command-line arguments that appear after the
class name in the java command to the application’s main
method as Strings in the array args.
 The number of arguments passed in from the command line is
obtained by accessing the array’s length attribute.

54
Command-line arguments
 For example, the command
 "java MyClass a b" passes two command-line

arguments, a and b, to application MyClass.


 Note that command-line arguments are separated by

white space, not commas.


 When this command executes, MyClass’s main

method receives the two-element array args (i.e.,


args.length is 2) in which args[ 0 ] contains the String
"a" and args[ 1 ] contains the String "b".
 Common uses of command-line arguments include

passing options and file names to applications.


55
Command-line arguments
public class InitArray{
public static void main(String args[]){
// check number of command-line arguments
if(args.length != 3)
System.out.println("Error: Please re-enter the entire command, including\n" + "an array size, initial value and
increment." );
else{
// get array size from first command-line argument
int arrayLength = Integer.parseInt( args[ 0 ] );
int array[] = new int[ arrayLength ]; // create array
// get initial value and increment from command-line arguments
int initialValue = Integer.parseInt( args[ 1 ] );
int increment = Integer.parseInt( args[ 2 ] );
// calculate value for each array element
for ( int counter = 0; counter < array.length; counter++ )
array[ counter ] = initialValue + increment * counter;
System.out.printf( "%s%8s\n", "Index", "Value" );
// display array index and value
for ( int counter = 0; counter < array.length; counter++ )
System.out.printf( "%5d%8d\n", counter, array[ counter ] );
} // end else
56
} // end main
} // end class InitArray
Compiling many classes
 In different files
 Both must be compiled
 e.g javac A.java B.java
 Only class with main method should be run(executed)

 In the same file


 Only class with main method should be public
 .class files are produced for both

57
Composition (has-a)
 A class can have references to objects of other
classes as members.
 Such a capability is called composition and is

sometimes referred to as a has-a relationship.

58
Composition (has-a)
class Employee{
int id;
String name;
Address address;//Address is a class
...
}

59
Composition (has-a)
class Operation{
int square(int n){
return n*n;
}
}
class Circle{
Operation op;//aggregation
double pi=3.14;
double area(int radius){
op=new Operation();
int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
return pi*rsquare;
}
public static void main(String args[]){
Circle c=new Circle();
double result=c.area(5);
System.out.println(result);
} 60
}
final Keyword
 placed before class, method or variable
 a final class cannot be subclassed

 a final method cannot be overridden by

subclasses
 a final variable can only be initialized once

 If a final variable is not initialized, a compilation

error occurs.

61
Final keywors
e.g //client class
package lesson1; Public class MyClass{
Public class Hello { public static void main(String
args[]){
public final double PIE;
Hello hel = newHello();
Hello(){
//hel.pie = 10;
pie = 3.14;
}
}
}
}

62
Static Keyword Example
publicclass Hello {
Public static int age;
Public static String doSomething(String messege){
Return messege;
}
public String doSomethingElse(String messege){
Return messege;
}}
//client class
Public class MyClass{
publicstaticvoid main(String args[]){
//all instances hel1,hel2,hel 3 share same static member
Hello hel1 = newHello();
Hello hel2 = newHello();
Hello hel3 = newHello();
Hello.doSomething("Said");
hel1.doSomethingElse("Java");
Hello.age = 10;
System.out.println(Hello.age); 63

}}
Creating your own Packages
 placed before class, method or variable
 a final class cannot be subclassed

 a final method cannot be overridden by

subclasses
 a final variable can only be initialized once

 If a final variable is not initialized, a compilation

error occurs.

64
Creating your own Packages
 Packaging
 package packageName;

 Importing
 import packageName ClassName;

 For multiple classes


 Import packageName .*;
 javac -d . Time1.java
 -d specifies exact directory to store a class 65

You might also like