Java OOP Concepts and Examples Guide
Java OOP Concepts and Examples Guide
Chapter One
OOP: - is the different method of thinking about programming using objects and class.
In procedural language we think separately about data and how the method interacts with data.
OOP forces us to think in terms of objects and the data interact between objects.
OOP enables us to model real world problems through programs in logical manner.
Because:-
o We can debug,
o Modify and
o Maintain easily
- We can reuse much of our code than with the case of procedural languages.
- OOP is the most usable and maintainable programming due to the following featurs:
Abstraction
Encapsulation
Inheritance
Polymorphism
Class
Object etc.
a. Abstraction: - is the way of collecting relevant information from the existing problems
such as attributes and methods.
It is the act of identifying objects to model problem domain.
Classes are abstracted from concepts or real world problems.
Objected are instantiated from class.
It is the first step of identifying classes and attributes that will be used in your
application.
b. Encapsulation: - the goal of OOP is to differentiate the use of an object from the
implementation of that object.
To accomplish this through data hiding /binding.
It is the grouping of related items into one unit.
Attributes and method or behaviors are encapsulated to create object.
c. Inheritance:- driving a new class(subclass) from the existing class(super class).
Have parent-child relationship or method.
The subclass inherits all the functionality from the super class.
1
Object Oriented Programming with Java book Prepared by: Melesew M.
Example:
String Stud_Name;
int age;
Student stud;
stud.Stud_Name=”Abel” ;
stud.age=24;
System.out.println(stud.Stud_Name);
System.out.println(stud.age);
}
}
What is java?
2
Object Oriented Programming with Java book Prepared by: Melesew M.
Java is an open standard, language specification, publicity, freely available, open source
language.
It is the current hot programming.
It is platform independent.
It is more secure.
Java features:
- Simple and object oriented
- Portability
- Availability
- Library
- Others
3
Object Oriented Programming with Java book Prepared by: Melesew M.
Control statement
Repeation statement
Branching statement
Variables
dataType variableName=value;
- Variable declaration:
e.g. public int x=5;
o operators(increment/decrement)
postfix x++, x--;
prefix ++x, --x;
o Arithmetic operator
* / - + %
o Relational operation
< > <= >=
o Assignment operator
= += -= *= /= == != ʌ
e.g. 2ʌ3=8 (2 power of 3)
o Logical operator
|| && !
Rule
o About syntax error.
o Not use special character. e.g. (.) dot, ?, space, …
o Must start with a letter or underscore. e.g.
int 1a; -------------------- wrong
int abc123; --------------- correct
$salary; ------------------ correct
_abc; --------------------- correct
? name; ------------------- wrong
first name; --------------- wrong
4
Object Oriented Programming with Java book Prepared by: Melesew M.
Convention
o Letters must be typed all either in upper case or lower case. But smaller letters are
more recommended.
e.g. String firstName;
int numberOfStudents;
Variable name should match to the value it holds.
e.g. String fname=”Abebe”;
int x=10;
float y=33.5;
String first_Name=”Melesew”;
if
o Syntax: if(expression | condition){
Statement(s);
}
if ------else
o Syntax: if(expression | condition){
Statement(s);
}else{
Statement(s);
}
if -------elseif------else
o Syntax: if(expression | condition){
Statement(s);
}elseif((expression | condition){){
Statement(s);
}else{
Statement(s);
}
5
Object Oriented Programming with Java book Prepared by: Melesew M.
switch
o Syntax: switch(expression)
{
case 1 value:
Statement(s)
break;
…
Default:
Statement(s);
break;
continue and break
- Used mostly in repetition statements.
Solution:
int x=10;
if(x%2==0)
System.out.println(x +” is+” even.”);
else
System.out.println(x +” is+” odd.”);
Example 2: Write a java program that finds the maximum number from the list.
int i,min,max,n;
n = input.nextInt();
for(i=0;i<n;i++)
arr[i]=input.nextInt();
6
Object Oriented Programming with Java book Prepared by: Melesew M.
min=max=arr[0];
for(i=0;i<n;i++)
if(arr[i]<=min)
min=arr[i];
for(i=0;i<n;i++)
if(arr[i]>=max)
max=arr[i];
System.out.println("\t===============================");
Example 3: Write a java program that determines a given student is either passed or failed.
package Status;
import java.util.Scanner;
int mark;
mark = input.nextInt;
if(mark>=50)
System.out.println(“Passed”);
else
System.out.println(“Failed”);
7
Object Oriented Programming with Java book Prepared by: Melesew M.
Example 4: Write a java program that determines a given student grade based on mark.
package Status;
import java.util.Scanner;
int mark;
mark = input.nextInt;
if(mark>=90)
System.out.println(“A”);
elseif(mark>=80)
System.out.println(“B”);
elseif(mark>=70)
System.out.println(“C”);
elseif(mark>=50)
System.out.println(“D”);
elseif(mark>=40)
System.out.println(“F”);
else
System.out.println(“FX”);
Example 5: write a java program that displays day of a week when a user type number from 1-7
for instance when press 1 it shows “Monday”
package days;
8
Object Oriented Programming with Java book Prepared by: Melesew M.
import java.util.Scanner;
String name;
int day;
day = input.nextInt;
switch(day){
case 1:
System.out.println(“Monday”);
break;
case 2:
System.out.println(“Tuesday”);
break;
case 3:
System.out.println(“Wednsday”);
break;
case 4:
System.out.println(“Thursday”);
break;
case 5:
System.out.println(“Friday”);
break;
case 6:
System.out.println(“Saturday”);
break;
case 7:
System.out.println(“Sunday”);
break;
9
Object Oriented Programming with Java book Prepared by: Melesew M.
default:
System.out.println(“Invalid input!”);
break;
}
}
}
Repeation Statement
while ---loop
do------while
for loop
i. while loop : -
pre test
Syntax: initialization;
while(condition){
statement(s);
increment / decrement;
}
ii. do-----while
Syntax: initialization;
do{
statement(s);
increment / decrement;
}while(condition);
iii. for---loop
Syntax:
a. for(initialization;condition;incerement/decrement)
{
Statement(s);
}
b. initialization;
10
Object Oriented Programming with Java book Prepared by: Melesew M.
for(;condition;)
incerement/decrement;
Example: Write a java program that adds a number from 0-10 using for loop, while loop and do
while loop.
//for loop
for(int i=0;i<=10;i++)
sum+=i;
System.out.println(“Sum=”+sum);
System.out.println(“i=”+i);
//while loop
int i=0,sum=0;
while(i<=10)
sum+=i;
i++;
System.out.println(“Sum=”+sum);
System.out.println(“i=”+i);
//do-while loop
int i=0,sum=0;
do{
sum+=i;
i++;
} while(i<=10);
11
Object Oriented Programming with Java book Prepared by: Melesew M.
System.out.println(“Sum=”+sum);
System.out.println(“i=”+i);
Array
or
or
int[] x= {3,2,5,8,9};
- The difference between array and pointer is pointer doesn’t declare with size but array can.
x[0]=3;
x[2]=7; // to change 5 to 7
System.out.println(x[4]); // Output 8 single value
for(int i=0;i<5;i++)
{
System.out.println(x[i]); // to print all elements of an array
}
Output// 3 2 7 9 8
12
Object Oriented Programming with Java book Prepared by: Melesew M.
e.g1. write a java program that can accept 10 students name using array.
package Adder;
import java.util.Scanner;
import java.util.Arrays;
int i;
for(i=0;i<10;i++)
arr[i] = input.nextLine();
for(i=0;i<10;i++)
System.out.print(i+1);
System.out.println(arr[i]);
e.g2. Write a java code that can accept 10 integer values and find sum, average and display their
values of the array in ascending order.
package Stud;
import java.util.Scanner;
import java.util.Arrays;
13
Object Oriented Programming with Java book Prepared by: Melesew M.
int i,j;
float sum=0,average;
for(i=0;i<10;i++)
{
num[i] = input.nextInt();
}
for(i=0;i<10;i++)
{
Sum = sum+num[i];
}
average = sum/10;
Arrays.sort(num);
for(i=0;i<10;i++)
{
System.out.print(num[i]);
}
}
}
package Array;
14
Object Oriented Programming with Java book Prepared by: Melesew M.
for(int j=0;j<3;j++){
System.out.print(x[i][j]+" ");
}
System.out.println();
}
}catch(Exception err){
System.out.println(err.getMessage());
}
}
}
package Array;
import javax.swing.*;
import java.util.*;
import java.io.*;
System.out.println(name[0][2]+" "+name[1][0]);
System.out.println(name[0][0]+" "+name[1][0]);
Observe the following example to show how two or more different arrays used in a class
package com.company;
import java.util.*;
public class Main {
public int id,i,n;
String name;
15
Object Oriented Programming with Java book Prepared by: Melesew M.
for(i=0;i<nn;i++){
System.out.println("Enter id : ");
id[i] = input.nextInt();
System.out.println("Enter name : ");
name[i] = input.next();
}
System.out.println("===============================");
System.out.println("\t ID Number .... Name ");
for(i=0;i<nn;i++){
System.out.print("\t"+id[i]+" ....... ");
System.out.print("\t"+name[i]);
System.out.println();
}
System.out.println("===============================");
}
import java.util.*;
String studname,studid;
int studage;
studname=sname;studid=sid;studage=sage;
System.out.println(studname+" "+ studid +" "+studage);
try{
16
Object Oriented Programming with Java book Prepared by: Melesew M.
int n;
System.out.print("how many data you accept ? : ");
n = get.nextInt();
for(int i=0;i<n;i++)
{
System.out.println("Enter name,id and age of student "+(i+1));
stud[i]=new studentinfo();
stud[i].studname=get.next();
stud[i].studid=get.next();
stud[i].studage=get.nextInt();
}
System.out.println("Student Name Student Id Student age");
System.out.println("==========================================");
for(int i=0;i<=2;i++)
studinfo.displaystudentinfo(stud[i].studname, stud[i].studid,
stud[i].studage);
}catch(Exception e){
System.out.println(e.getMessage());
17
Object Oriented Programming with Java book Prepared by: Melesew M.
More examples
// write a java program that determines a given number is Armstrong or not.
package ArmstrongNumber;
int c=0,a,temp;
int n=153;
temp=n;
while(n>0){
a=n%10;
n=n/10;
c=c+(a*a*a);
if(temp==c){
System.out.println(temp+" is armstrong.");
}else{
18
Object Oriented Programming with Java book Prepared by: Melesew M.
int r,sum=0,temp;
int n=454;
temp=n;
while(n>0){
r = n%10;
sum = (sum*10)+r;
n = n/10;
if(temp==sum){
}else{
int n1=0,n2=1,n3;
int i;
19
Object Oriented Programming with Java book Prepared by: Melesew M.
int count=10;
System.out.println("n1+n2");
for(i=2;i<count;i++){
n3 = n2 + n1;
System.out.println(" "+n3);
n1 = n2;
n2 = n3;
/Output
To sort an arrays:
o Arrays.sort(arrayName);
20
Object Oriented Programming with Java book Prepared by: Melesew M.
Chapter Two
Class declaration
class :- keyword used to create class and must be small letter case.
21
Object Oriented Programming with Java book Prepared by: Melesew M.
o Method contains:-
class Circle{
double radius;
double findArea(){
return radius * radius;
}
}
package studentinfo;
void show(){
System.out.println(id+" "+name);
}
22
Object Oriented Programming with Java book Prepared by: Melesew M.
System.out.println("ID Name");
System.out.println("-------");
s1.show();
s2.show();
}
}
Example 1: The following example show how class and object created correctly.
package StudentClass;
System.out.println("Name : "+stud.name);
System.out.println("Age : "+stud.age);
}
}
23
Object Oriented Programming with Java book Prepared by: Melesew M.
Object declaration
className objectName; or
Instantiated object
o objectName = new className(arg.); // we can make also empty for default constructor
To call an object
o objectName.identifierName;
o variable name:-
package EmployeeDetails;
void display(){
System.out.println(name+" "+position+" "+salary);
}
24
Object Oriented Programming with Java book Prepared by: Melesew M.
ed1.display();
ed2.display();
}
}
//Output
Variables:
Constructor
25
Object Oriented Programming with Java book Prepared by: Melesew M.
i. Default(non-parameterized constructor)
package Circle;
Circle(){
radius=2;
}
26
Object Oriented Programming with Java book Prepared by: Melesew
- To set access level java uses access modifiers for class, variables and methods.
default:- visible to the package.
private:- visible to the class only.
public:- visible to the world.
visible to the package and all classes.
protected:-visible
package AccessModifiers;
27
Object Oriented Programming with Java book Prepared by: Melesew M.
// e.g2:
package AA;
public class AA {
public String color="red";
public float price;
class B{
AA x = new AA();
x.price=25f;
System.out.println(x.color);
System.out.println(x.price);
}
}
this
final
static
super
Example: The following exercise shows how class, variable as well as methods
can we construct/deploy.
package employee;
28
Object Oriented Programming with Java book Prepared by: Melesew M.
public employee(){
name="The default name:";
country="The default country:";
}
public employee(String newName, String newCountry){
name=newName;
country=newCountry;
}
public static void main(String[] args) {
Creating constructor
No return type specified even void.
Class name start with capital letter & the class name is Pascal based.
o e.g. public myClass (parameterType parameterName);
The constructor names always match with class name.
29
Object Oriented Programming with Java book Prepared by: Melesew M.
Default constructor
- The new operator allocates the memory for the new object (instance).
- The constructor call initializes the new object at the time of creation.
- Argument doesn’t specify any data type.
e.g. Scanner input = new Scanner(System.in);
30
Object Oriented Programming with Java book Prepared by: Melesew M.
Example 1: The following example explains how to use static variables in java
package Student;
public class Student {
int id;
String name;
static String college="Technology"; //Static variable declaration
Student(int i, String n){
id=i;
name=n;
}
void display(){
System.out.println(id+" "+name+" "+college);
}
public static void main(String[] args) {
Student s1 = new Student(12,"Melesew");
Student s2 = new Student(13,"Azeb");
s1.display();
s2.display();
}
}
Example 2:
package Counter;
Counter(){
count++;
System.out.println(count);
}
31
Object Oriented Programming with Java book Prepared by: Melesew M.
- If you apply static keyword with any method it is known as static method.
- A static method belongs to the class rather than objects of a class.
- Static methods can be invoked without the need for creating an instance of a class.
- A static method can access static data members and change the value of it.
Example 1: The following example explains how to use static methods in java
package Student;
void display(){
System.out.println(id+" "+name+" "+college);
}
s1.display();
s2.display();
s3.display();
} }
32
Object Oriented Programming with Java book Prepared by: Melesew M.
e.g.
package A;
public class A {
static{
System.out.println("Static blok invoked.");
}
System.out.println("Hello World!");
}
}
o In static block we can output the data without main function i.e. by using static keyword.
33
Object Oriented Programming with Java book Prepared by: Melesew M.
Example 1: The following example describes how to use this keyword in java both for variables
and methods/constructors.
package Student;
void display(){
System.out.println(id+" "+name);
}
s1.display();
s2.display();
Student s3 = new Student();
s3.display();
}
}
Example 2: The following example describes how to write java program variables which are
assigning a value to another variable without using this keyword.
package Student;
34
Object Oriented Programming with Java book Prepared by: Melesew M.
import java.util.*;
int id;
String name;
Student(){
System.out.println("================================");
this();
id=i;
name=n;
System.out.println("================================");
System.out.println("\t"+id+" "+name);
System.out.println("================================");
int a;
String b;
a=input.nextInt();
b=input.next();
s1.display();
35
Object Oriented Programming with Java book Prepared by: Melesew M.
Example 3: The following example describes how to write java program variables which are
package Person;
void msg(int x,int y){ //Check output if this keyword not used in the variables
this.x=x;
this.y=y;
System.out.println(x+" "+y);
}
package Student;
36
Object Oriented Programming with Java book Prepared by: Melesew M.
int id;
String name;
String city;
void display(){
System.out.println(id+" "+name+" "+city);
}
s1.display();
s2.display();
}
}
- A class which has the same package are stored in the same folder.
e.g.
package Computer;
37
Object Oriented Programming with Java book Prepared by: Melesew M.
show();
show("melesew");
}
}
package A;
public class A {
void m(){
System.out.println("Method is invoked.");
}
void n(){
this.m();
}
void p(){
n();
}
A a1 = new A();
a1.p();
}
}
- By default we can access subclass variable if there is similar variable is declared in the
parent and subclass unless to call the parent variable class by super () variable.
38
Object Oriented Programming with Java book Prepared by: Melesew M.
Chapter Three
i. Inheritance
- It is a mechanism in which one object acquires all the properties and behaviors of parent
object.
achieved.
Syntax of inheritance
The “extends” keyword indicates that you are making a new class that drives from
In terminology of java:
39
Object Oriented Programming with Java book Prepared by: Melesew M.
package Employee;
class Test{
//Output
40
Object Oriented Programming with Java book Prepared by: Melesew M.
Types of inheritance
Single
Multiple / multi-level
Hierarchical
only.
- Multiple and hybrid inheritance is not supported in java unless we have interface.
- To refer complexity and simplify the language, multiple inheritance is not supported in java
41
Object Oriented Programming with Java book Prepared by: Melesew M.
//an example of multiple-inheritance in java and compiler error wills occurs because of the above
reasons:
package A;
public class A {
void msg(){
System.out.println("Hello");
}
}
class B {
void msg(){
System.out.println("Welcome");
}
}
class C extends A,B{ //error occurs because multiple inheritance not supported in java but possible in interface
Aggregation in java
Example: //
package Address;
42
Object Oriented Programming with Java book Prepared by: Melesew M.
class emp{
int id;
String name;
Address ad;
void display(){
System.out.println(id+" "+name+" "+ad.city+" "+ad.state+" "+ad.country);
}
e1.display();
e2.display();
}
}
//Output
43
Object Oriented Programming with Java book Prepared by: Melesew M.
Super keyword
//example:
package Vecihle;
void display(){
System.out.println("Bike class speed : "+speed); //Without super() keyword
System.out.println("Vecihle class speed : "+super.speed); //With super() keyword
}
44
Object Oriented Programming with Java book Prepared by: Melesew M.
//example:
package Vecihle;
Vecihle(){
System.out.println("Vecihle is created.");
}
}
Bike(){
super(); //used to invoke parent class constructor
System.out.println("Bike is created.");
}
- Only accessible inside the method of the class in which they are declare.
The super keyword used in case subclass contains same method name as parent class.
Example:
package Person;
void msg(){
System.out.println("Hello");
45
Object Oriented Programming with Java book Prepared by: Melesew M.
}
}
Final keyword
Variable
Methods, and
Class
- A final variable that has no value is called “blank final variable” or “uninitialized final variable”.
- The blank final variable can be static also will be initialized in the static block only.
46
Object Oriented Programming with Java book Prepared by: Melesew M.
Stop inheritance
- If you make any variable as final, you cannot change the value of final variable i.e it is
constant.
//example
package Bike;
public class Bike {
final int speed=90; // final variable declaration & intialization
void run(){
speed=40; //error will occure because final variables can't be changed
System.out.println(speed);
}
public static void main(String[] args) {
Bike b = new Bike();
b.run();
}
}
//example
pckage Bike;
47
Object Oriented Programming with Java book Prepared by: Melesew M.
- If you make any class as final, you can’t extend (inherit) it.
//example
package Bike;
void run(){
System.out.println("Hello");
}
}
class Handa extends Bike{ //error displayed because final class can't be extended
void run(){
System.out.println("Hello from Handa class");
}
ii. Polymorphism
48
Object Oriented Programming with Java book Prepared by: Melesew M.
- Polymorphism comes from Greek word means “many forms” or many shape (different shape).
- In java polymorphism refers to the fact that you can have multiple methods with the same
Overloading (Method)
//example
package Test;
myPrint(5);
myPrint(5,3);
}
//Output
Overriding (Method)
49
Object Oriented Programming with Java book Prepared by: Melesew M.
Example:
package MethodOverwrite;
import java.util.*;
//default constructor
public Main(){
System.out.println("default constructor is invoked");
}
50
Object Oriented Programming with Java book Prepared by: Melesew M.
m.display(gender);
}
}
//Output
Create a method in a sub class having the same signature as a method in super class.
The type of argument is different and the number of argument are different also is called
overloading.
Method overloading can be done in similar class (super class) or (sub class).
Method overloading can be implemented by different classes (i.e. super class and sub
class).
Abstraction
abstract method();
here,
51
Object Oriented Programming with Java book Prepared by: Melesew M.
o Abstract class: - can contain either abstract or non-abstract method & have body.
abstract method();
}
Non-abstract method has body.
e.g.
It is the process of hiding the implementation details and showing only functionality to
Abstract class
52
Object Oriented Programming with Java book Prepared by: Melesew M.
Abstract Method
- Any class that extends an abstract class must implement all the abstract methods of the
//example:
void msg();
e.g.
package Test;
class C extends B{
53
Object Oriented Programming with Java book Prepared by: Melesew M.
void msg(){
System.out.println("Hello");
void n(){
System.out.println("World.");
C c = new C();
c.msg();
c.m();
c.n();
//Output
Interface
It has static constants (as data member) and abstract method (as a method) only.
Java compiler adds public and abstract keyword before the interface method.
Syntax:
54
Object Oriented Programming with Java book Prepared by: Melesew M.
interface interfaceName;
//data members
// method(s)
Example1:
interface printable{
int MIN=5;
void print();
interface printable{
Example2:
package Printable;
interface Printable {
void print();
System.out.println("Hello");
55
Object Oriented Programming with Java book Prepared by: Melesew M.
obj.print();
Example 3:
package Showable;
interface Showable {
abstract void show();
}
interface Printable {
abstract void print();
}
Java package
56
Object Oriented Programming with Java book Prepared by: Melesew M.
Package class
Example//
import java.util.Scanner;
import java.util.*;
import regular.x;
class A {
void msg(){
System.out.println(“from class extended”);
}
}
package summer;
import regular.*;
import regular.A;
class F{
public static void main(String… args){
A obj = new A();
Obj.msg();
}
}
IT(package) Packages
Regular - A
-B classes
-C
Summer -D
-E
57