OOP Lecture 04
OOP Lecture 04
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
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
method
Arguments are data values passed to parameters
expressions.
6
Methods-Parameters and
Arguments
//Declaration of a method with parameters
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
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();
}
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
method
constructor
block
25
Class Vs Object
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
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.
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.
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!" );
}
}
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 ); } }
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
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
57
Composition (has-a)
A class can have references to objects of other
classes as members.
Such a capability is called composition and is
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
subclasses
a final variable can only be initialized once
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
subclasses
a final variable can only be initialized once
error occurs.
64
Creating your own Packages
Packaging
package packageName;
Importing
import packageName ClassName;