Vous êtes sur la page 1sur 4

7 JAVA Object-Oriented Programming Concept

By placing a boundary around the properties and methods of our objects,


we can prevent our programs from having side effects wherein programs have
their variables changed in unexpected ways.

At the end of the lesson, the student should be able to:


Explain object-oriented programming and some of its concepts
Differentiate between classes and objects
Differentiate between instance variables/methods and class (static)
variables/methods
Explain what methods are and how to call and pass parameters to
methods
Introduction to Object-Oriented Programming
- Object-Oriented Programming (OOP)
A programming paradigm that revolves around the concept of objects as the
basic elements of your programs. These objects are characterized by their
properties and behaviors.

Inheritance
Different kinds of objects often have a certain amount in common with
each other. Yet each also defines additional features that make them different:
tandem bicycles have two seats and two sets of handlebars; road bikes have
drop handlebars; some mountain bikes have an additional chain ring, giving them
a lower gear ratio.
Object-oriented programming allows classes to inherit commonly used state and
behavior from other classes.
Classes and Objects
To differentiate between classes and objects, let us discuss an example:

Object
is composed of a set of data (properties) which are variables describing the
essential characteristics of the object, and consists of a set of methods
(behavior) that describes how an object behaves.
An object is an instance of a class.
Example of objects

Classes provide the benefit of reusability.


Software programmers can use a class over and over again to create
many objects.

objects in the physical world can easily be modeled as software objects using the
properties as data and the behaviors as methods.
Class
can be thought of as a template, a prototype or a blueprint of an object
is the fundamental structure in object-oriented programming
Two types of class members:
Fields (properties or attributes) - specify the data types defined
by the class
Methods - specify the operations

Class Instantiation
To create an object or an instance of a class, we use the new operator.
For example, if you want to create an instance of the class String, we write the
following code,
String str2 = new String(Hello world!);
or also equivalent to,

Concept of OOP
Encapsulation
It is the method of hiding certain elements of the implementation of a
certain class.

String str2 = "Hello world!";

<parameter> The parameter_list is a comma-separated list of identifiers and


their type declarations. These identifiers, called formal parameters, are used
within the body of the method. The role of parameters is to act as placeholders
for actual values that are passed to the method when it is called.
The most common method that we use is the main method

Another example that we already discussed


Scanner scan = new Scanner(System.in);

public static void main (String args[]) {


System.out.println (Hello world!);
}
another example:
public static void computeSum(int x, int y) {
System.out.print(The sum is + (x+y));
}

The new operator


allocates a memory for that object and returns a reference of that memory
location to you.
When you create an object, you actually invoke the class' constructor.
Methods
Method
is a separate piece of code that can be called by a main program or
any other method to perform some specific function.

The method above has two parameters and displays the sum.
public static int computeSum(int x, int y) {
int sum=x+y;
return sum;
}

The following are characteristics of methods:


It can return one or no values
It may accept as many parameters it needs or no parameter at all.
Parameters are also called arguments.
After the method has finished execution, it goes back to the method
that called it.

The method above has two parameters and return the sum where the method is
called.

Why Use Methods?


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.
Declaring Method

To call a method,
<methodName>(<parameter>);
*This is only applicable to methods within the same class
Example:
message();
computeSum(5,10);
computeSum(a,b);
Sample program that uses the computeSum method:
public class UsingComputeSum{
public static void main(String args[]){
int sum, a=20, b=30;
//call computeSum and pass the value of a and b
sum=computeSum(a,b);
System.out.println(The sum is + sum);
}

To declare methods we write,


<modifier> <returnType> <name>(<parameter>) {
Statements;
<return statement>; //if any
}
where,
<modifier> can carry a number of different modifiers (public / private)
<returnType> can be any data type (including void)
<returnStatement> used to return a value and/or causes an immediate exit
from the method it is in.
<name> can be any valid identifier

public static int computeSum(int x, int y) {


int sum=x+y;
return sum; //return the value of sum
}
}

A method may not have parameter list and it may not return any value.

Using the previous example computeSum method, we will just omit the word
static
public void computeSum(int x, int y) {
System.out.print(The sum is + (x+y));
}
computeSum method is now an instance method

public class DisplayMessage{


public static void main(String args[]){
msg();
}

Calling Instance Method


- Before we can call an Instance method we need first to instantiate an object of
the class which the instance method belongs.
- After creating an object we can now call an instance method, it is written in the
format
nameOfObject.nameOfMethod( parameters );

public static void message(){


System.out.println(Hello World!);
}
}
2 Types of Method
1. Static methods
Static methods are methods that can be invoked without
instantiating a class (means without invoking the new keyword).
Static methods belong to the class as a whole and not to a certain
instance (or object) of a class.
Static methods are distinguished from instance methods in a class
definition by the keyword static.

Let's take two sample methods found in the class String,

Examples of static methods based on our discussions are:


main method
computeSum method
message method
Calling Static Methods
To call a static method just type,
With parameter(s):
Classname.staticMethodName(parameter(s));

Using the methods,

Without parameter:
Classname.staticMethodName();

String str1 = "Hello"; //instantiate str1 as String object


char x = str1.charAt(0);
*the above code will return the character H and store it to variable x

Examples of static methods, we've used so far in our examples are,

String str2 = "hello";


boolean result = str1.equalsIgnoreCase( str2 );

//prints data to screen


System.out.println(Hello world);

*the above code will return a boolean value true

Another example:
//converts the String 10, to an integer
int i = Integer.parseInt(10);

Scope of a Variable
The scope
determines where in the program the variable is accessible.
determines the lifetime of a variable or how long the variable can exist in
memory.

2. Instance Method
Instance methods are methods that need an object to be used.
Instance method belongs to the instantiated object of a class.

The scope is determined by where the variable declaration is placed in


the program.
To simplify things, just think of the scope as anything between the curly
braces {...}. The outer curly braces are called the outer blocks, and the
inner curly braces are called inner blocks.
A variable's scope is inside the block where it is declared, starting from
the point where it is declared, and in the inner blocks.

your compiler will generate an error since you should have unique names for
your variables in one block.
However, you can have two variables of the same name, if they are not declared
in the same block. For example,
int test = 0; System.out.print( test );
//..some code here
{
int test = 20; System.out.print( test );
}
Coding Guidelines
Avoid having variables of the same name declared inside one
method to avoid confusion.

Exercises
Class name: UsingStaicMethod
1. Create a program that will ask for the grades in Math, Science, English
and Computer Science of a student. Create computeAve as static
method to compute and display the average of the grades.
Class name: UsingInstanceMethod
2. The same problem with Exercise No. 1 but change computeAve from
static method to instance method.
In the main method, the scopes of the variables are,

Class name: UsingReturn


3. The same problem with Exercise No. 1 but the computeAve will now
compute and return the average of the grades.

ages[] - scope A
i in B - scope B
i in C scope C

Class name: OddEven


4. Create a program that will ask for 10 values of an array of integer. Create
countEven method to count and return the number of even numbers and
countOdd method to count and return the number of odd numbers.

In the test method, the scopes of the variables are,

arr[] - scope D
i in E - scope E

When declaring variables, only one variable with a given identifier or name can
be declared in a scope.
That means that if you have the following declaration,
{
int test = 10;
int test = 20;
}

Vous aimerez peut-être aussi