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

Object-Oriented Programming in Java: College of Science Department of Computer Programing Fundamentals (Java) First Stage

The document summarizes object-oriented programming concepts in Java, including: 1. Objects have state (attributes like type and color) and behavior (methods like changeSpeed). A class defines a blueprint for objects. 2. Variables can be instance variables (unique to each object), class variables (shared by all objects), local variables (only accessible within a method), or parameters (passed into a method). 3. Methods define reusable blocks of code and can return values or be void. The main method is required to run a Java program.

Uploaded by

bashdar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Object-Oriented Programming in Java: College of Science Department of Computer Programing Fundamentals (Java) First Stage

The document summarizes object-oriented programming concepts in Java, including: 1. Objects have state (attributes like type and color) and behavior (methods like changeSpeed). A class defines a blueprint for objects. 2. Variables can be instance variables (unique to each object), class variables (shared by all objects), local variables (only accessible within a method), or parameters (passed into a method). 3. Methods define reusable blocks of code and can return values or be void. The main method is required to run a Java program.

Uploaded by

bashdar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

College of Science

Department of Computer
Programing Fundamentals (Java)
First Stage

Object-Oriented Programming in
Java
Prepared by:
Ari M.Saeed
2018 - 2019
 
Object-Oriented Programming in Java

Object-oriented programming (OOP) is a programming language model organized


around objects.

Object: Any entity that has state and behavior is known as an object. For example:
chair, pen, table, keyboard, bike etc. It can be physical and logical.

2
 
Object-Oriented Programming in Java

Real-world objects share two characteristics: State and Behavior.

• Cars have state or attribute (type, color, model).


• Cars also have behavior (changeSpeed, openDoor).

An object stores:
• Its State in fields (variables in some programming languages).
• Its Behavior through methods (functions in some programming languages).

3
Classes
A class is a blueprint or a template for creating different objects.

• The keyword class begins the class definition for a class named  StudentApp.


• The code for each class appears between the opening and closing curly braces
marked in bold below.

class StudentApp {
//variables
//methods
//constructors
..
}
4
 Kinds of Variables
1- Instance Variables (Non-Static Fields):
• fields declared without the static keyword.
• Non-static fields are also known as instance variables.
• instance variables mean their values are unique to each instance of a class(to
each object, in other words).

2- Class Variables (Static Fields):


• A class variable is any field declared with the static modifier.
• This tells the compiler that there is exactly one copy of this variable in
existence. For example:
static final float PI = 3.14;
• Additionally, the keyword final could be added to indicate that the number of
gears will never change.
5
 Kinds of Variables
3- Local Variables: 
• A local variable is a variable that’s declared within the body of a method.
• It can be used this variable only within that method.
• They are not accessible from the rest of the class.

4- Parameters
• A parameter is a variable that you pass in to a method.
• The args variable is the parameter variable in the main method public static
void main(String[] args).

6
 Kinds of Variables
Class Variable
(Static Field)
class Hotel{

final static int noOfRooms=5; Instance Variable


(Non-Static Field)

int noOfGuests=12;
Parameter

public static void main(String[] args) {

short rentRoom=35;
Local Variable

}
}
7
Creating Instances (Objects ) of a Class
• An instance is a particular item of a class.
• For example, you can define a class called "Student" and create three instances of
the class "Student" for “Ahmad", “Shko" and “Kardo".
• The term "object" usually refers to instance. But it is often used loosely, which
may refer to a class or an instance.
class Student { String name; double grade;
void getName() { }
void printGrade(){ }
}
class Createobj {
Ali, Shko, and Kardo are
public static void main(String[] args) {
Objects (instances) of Class.
Student Ali=new Student();
Student Shko=new Student();
Student Kardo=new Student();
}} 8
Methods
A Java method is a collection of statements that are grouped together to perform an
operation.

public double makeMethod(double a, int b) {


//do the calculation here
}

The only required elements of a method declaration are:

the method's return type, name, a pair of parentheses, (), and a body between braces, {}.

Tips: Every program must have at least one method that called main method.
Methods
More generally, method declarations have six components, in order:

1. Modifiers—such as public, private, and others you will learn about later.
2. The return type—the data type of the value returned by the method, or void if the
method does not return a value.
3. The method name—the rules for field names apply to method names as well, but the
convention is a little different.
4. The parameter list in parenthesis—a comma-delimited list of input parameters,
preceded by their data types, enclosed by parentheses, (). If there are no parameters,
you must use empty parentheses.
5. An exception list—to be discussed later.
6. The method body, enclosed between braces—the method's code, including the
declaration of local variables, goes here.
Creating Method
Example:

public int getMin(int a, int b) {


int val;
if (a > b)
val = b;
else
val = a;

return val;
}
The main Method
In the Java programming language, every application must contain a main method
whose signature is:

public static void main(String[] args)

The main method accepts a single argument: an array of elements of type String.

Tips: When a program starts running, it has to start execution from somewhere. That
somewhere is called main.

12
Methods Type
1- Static methods: Is a method that can be called and executed without creating an object.
Static method can be invoked directly via class name.
Are declared with the keyword static.

class StudentApp {
public static void main(String[] args) {

Book.createBook();
}
}
class Book {
static void createBook() {

System.out.print("Psychology and Human Evolution");


}
}
13
Methods Type
2- Instance methods: are defined in a class which is only accessible through the
Object of the class are called Instance method.
Instance methods are declared without the keyword static.
class Book {
void createBook() {
System.out.print("Psychology and Human Evolution");
}
}
class StudentApp{
public static void main(String[] args) {

Book book1 = new Book();//book1 is an object to call CreateBook method


book1.createBook();
}
}
14
Method Calling
For using a method, it should be called.
There are two ways in which a method is called i.e., method returns a value or returning
nothing (no return value).
The process of method calling is simple. When a program invokes a method, the program
control gets transferred to the called method. This called method then returns control to the
caller in two conditions, when −

• The return statement is executed.


• It reaches the method ending closing brace.

Following is the example to demonstrate how to define a method and how to call it:
Method Calling
class callMethod {public static void main(String[] args) {
int a = 11;
int b = 6;
int c = getValue(a, b);
System.out.println("Minimum Value = " + c);
}
public static int getValue (int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else min = n1;
return min;
}}
The void Keyword
The void keyword allows us to create methods which do not return a value.

Here, in the following example we're considering a void method methodRankPoints.

This method is a void method, which does not return any value.

Call to a void method must be a statement i.e. methodRankPoints(255.7);.

It is a Java statement which ends with a semicolon as shown in the following example.
The void Keyword
public class ExampleVoid {
public static void main(String[] args) {
methodRankPoints(255.7);
}
public static void methodRankPoints(double points) {
if (points >= 202.5) {
System.out.println("Rank:A1");
}else if (points >= 122.4) {
System.out.println("Rank:A2");
}else {
System.out.println("Rank:A3");
}
}}
Passing Parameters by Value
While working under calling process, arguments is to be passed. These should be in the
same order as their respective parameters in the method specification. Parameters can be
passed by value or by reference.

Passing Parameters by Value means calling a method with a parameter. Through this, the
argument value is passed to the parameter.

Example

The following program shows an example of passing parameter by value. The values of the
arguments remains the same even after the method invocation.
Passing Parameters by Value
class swappingExample {public static void main(String[] args) {
int a = 30; int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);
swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be same here**:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}
public static void swapFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
// Swap n1 with n2
int c = a; a = b; b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}}
Passing Parameters by Value
This will produce the following result:

Output

Before swapping, a = 30 and b = 45


Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30

**Now, Before and After swapping values will be same here**:


After swapping, a = 30 and b is 45
Method Overloading
When a class has two or more methods by the same name but different parameters, it is
known as method overloading. It is different from overriding.

Let’s consider the example discussed earlier for finding minimum numbers of integer type.
If, let’s say we want to find the minimum number of double type.

Then the concept of overloading will be introduced to create two or more methods with the
same name but different parameters.
Method Overloading
The following example explains the same:
public static void main(String[] args) {
int a = 3; int b = 4;

int result1 = minFunction(a);

// same function name with different parameters


double result2 = minFunction(a,b);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}
Method Overloading
static int minFunction(int n1) {
int min=3;
min = min * n1;
return min;
} // one parameter
public static double minFunction(int n1, int n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;//two parameters
}
}
Method Overloading
This will produce the following result:
Output

Minimum Value = 9
Minimum Value = 3.0

Overloading methods makes program readable. Here, two methods are given by the same
name but with different parameters. The minimum number from integer and double types is
the result.
The Constructors
A constructor initializes an object when it is created. It has the same name as its class
and is syntactically similar to a method. However, constructors have no explicit return
type.

Typically, you will use a constructor to give initial values to the instance variables
defined by the class, or to perform any other startup procedures required to create a
fully formed object.

All classes have constructors, whether you define one or not, because Java
automatically provides a default constructor that initializes all member variables to
zero. However, once you define your own constructor, the default constructor is no
longer used.
The Constructors
Example
Here is a simple example that uses a constructor without parameters:
// A simple constructor.
class MyClass {
int x;

// Following is the constructor


MyClass() {
x = 10;
}
}
The Constructors
You will have to call constructor to initialize objects as follows:

class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.x + " " + t2.x);
}
}
Output

10 10
Parameterized Constructor
Most often, you will need a constructor that accepts one or more parameters.
Parameters are added to a constructor in the same way that they are added to a method,
just declare them inside the parentheses after the constructor's name.

Here is a simple example that uses a constructor with a parameter


// A simple constructor.

class MyClass {
int x;
// Following is the constructor
MyClass(int i ) {
x = i;
}}
Parameterized Constructor
You will need to call a constructor to initialize objects as follows:
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}
This will produce the following result:
Output
10 20
The this keyword
• This is a keyword in java which is used as a reference to the object of the current
class, with in an instance method or a constructor. Using this you can refer the
members of a class such as constructors, variables and methods.
• Note − the keyword this is used only within instance methods or constructors
The this keyword
In general, the keyword this is used to:
Differentiate the instance variables from local variables if they have same names, within
a constructor or a method.
class Student {
int age;
Student(int age) {
this.age = age;
}
}

Call one type of constructor (parametrized constructor or default) from other in a class.
It is known as explicit constructor invocation.
The this keyword
class Student {
int age
Student() {
this(20);
}
Student(int age) {
this.age = age;
}
}
Example
Here is an example that uses this keyword to access the members of a class. Copy and
paste the following program in a file with the name, This_Example.java.
The this keyword
Example
Here is an example that uses this keyword to access the members of a class. Copy and
paste the following program in a file with the name, This_Example.java.
References

Java in a Nutshell, 6th Edition, By David Flanagan,2015

Introduction to programing with java, John S.Dean,2008

http://java.sun.com/docs/books/tutorial

http://www.vogella.com

http://journals.ecs.soton.ac.uk/java/tutorial

https://www.tutorialspoint.com
35

You might also like