Object-Oriented Programming in Java: College of Science Department of Computer Programing Fundamentals (Java) First Stage
Object-Oriented Programming in Java: College of Science Department of Computer Programing Fundamentals (Java) First Stage
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: 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
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.
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).
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{
int noOfGuests=12;
Parameter
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.
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:
return val;
}
The main Method
In the Java programming language, every application must contain a main method
whose signature is:
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() {
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.
This method is a void method, which does not return any value.
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
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;
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;
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.
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
http://java.sun.com/docs/books/tutorial
http://www.vogella.com
http://journals.ecs.soton.ac.uk/java/tutorial
https://www.tutorialspoint.com
35