0% found this document useful (0 votes)
12 views57 pages

Java OOP Concepts and Examples Guide

The document is an introductory guide to Object Oriented Programming (OOP) using Java, covering fundamental concepts such as abstraction, encapsulation, inheritance, and polymorphism. It explains Java's features, the Java Development Kit (JDK), and the Java Virtual Machine (JVM), along with basic programming constructs like control statements, loops, and arrays. The document also includes practical examples of Java programs demonstrating various programming concepts and techniques.

Uploaded by

Tesfalegn Yakob
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views57 pages

Java OOP Concepts and Examples Guide

The document is an introductory guide to Object Oriented Programming (OOP) using Java, covering fundamental concepts such as abstraction, encapsulation, inheritance, and polymorphism. It explains Java's features, the Java Development Kit (JDK), and the Java Virtual Machine (JVM), along with basic programming constructs like control statements, loops, and arrays. The document also includes practical examples of Java programs demonstrating various programming concepts and techniques.

Uploaded by

Tesfalegn Yakob
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Object Oriented Programming with Java book Prepared by: Melesew M.

Chapter One

Introduction to OOP in Java

 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.

d. Polymorphism:-having many (different) forms.


e. Message passing:-the process of communication between objects b/c objects
communicate each other through message passing.
 We use dot(.) operator.
 Classes are entities.
 Entities have attributes and methods.

Example:

public class Student{

String Stud_Name;

int age;

public static void main(String[] args){

Student stud;

stud.Stud_Name=”Abel” ;

stud.age=24;

System.out.println(stud.Stud_Name);

System.out.println(stud.age);

}
}

What is java?

- It is a computer programming (OOP).


- OOP supports the concept of reusability.
- It is created by sun-micro system.
- The most common java programming are application and/or applets.
- Applets are used to develop web based applications.
- Applications: - are standalone programs.
- Applets are web based applications.
 Java programming language is a high level language that can be described as :
o An OOP that uses classes and objects.
o Very portable OOP language.
o Have large support class libraries that cover many general needs.
o Can create applets, applications, java server pages and more.

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

What is JDK /Java Development Kit?


 Stands for java development kit.
 A collection of programming tools including:
o java:- the loads of java applications
o javac
o applete Viewer
o java doc
o jar
o java ws (web starter)
o jstate
o jdb

What is java Virtual Machine?


- .class byte code
- JVM is the application that executes java program.
- JVM is available for many hardware and software platform.
- It is crucial components of java platforms.
- If we have JVM , java programming can run on:-
 Windows
 Linux
 Solaris
 MacOS

3
Object Oriented Programming with Java book Prepared by: Melesew M.

 Control statement
 Repeation statement
 Branching statement

Variables
dataType variableName=value;

 Primitive: - int, float, byte, boolean, double,


 Class: - data type, name, accessibility (specifier)
Syntax:

[Specifier] 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”;

Control statements (Conditional Statements)

 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.

Example1: Write a java program that checks a number is even or odd.

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.

public class max{

public static void main(String…args){

Scanner input = new Scanner(System.in);

int i,min,max,n;

int[] arr = new int[100];

System.out.println("How many numbers you need to enter ? :");

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===============================");

System.out.println("\t Minimum : "+min);

System.out.println("\t Maximum : "+max);

Example 3: Write a java program that determines a given student is either passed or failed.

package Status;

import java.util.Scanner;

public class Status{

public static void main(String… args){

Scanner input = new Scanner(System.in);

int mark;

System.out.println(“Enter your mark out of 100% ?”);

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;

public class Status{

public static void main(String… args){

Scanner input = new Scanner(System.in);

int mark;

System.out.println(“Enter your mark out of 100% ?”);

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;

public class Days{

public static void main(String… args){

Scanner input = new Scanner(System.in);

String name;

int day;

System.out.println(“Enter a number between 1-7 ? ”);

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;

c. for( ; ;) -------------used to create infinite loop.

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

- A collection of variable with the same type.

dataType[] arrayName = new dataType[size of array];


or
dataType arrayName[] = new dataType[size];
or
dataType[] arrayName ={ } ;

or

dataType[][] arrayName = { { },{ } };

or

dataType[][] arrayName = new dataType[size][size];

e.g. int[] arrInt = new int[5];

int[] x= {3,2,5,8,9};

- The difference between array and pointer is pointer doesn’t declare with size but array can.

- Arrays are always manipulated by index such as 0___(n-1)

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;

public class Adder {

public static void main(String[] args){

Scanner input = new Scanner(System.in);

int i;

String [] arr = new String[10];

System.out.println(“Enter 10 students name?: “);

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;

public class Stud {

13
Object Oriented Programming with Java book Prepared by: Melesew M.

public static void main(String[] args){

Scanner input = new Scanner(System.in);

int i,j;

float sum=0,average;

int[] num = new int[10];

System.out.println(“Enter 10 numbers : “);

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]);
}
}
}

Example: Do the following two dimensional arrays

package Array;

public class Array {

public static void main(String[] args) {


int[][] x = {{3,2,5},{4,3}};
try{
for(int i=0;i<3;i++){

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());
}
}
}

Example2: Do the following two dimensional arrays of string

package Array;

import javax.swing.*;

import java.util.*;

import java.io.*;

public class Array {

public static void main(String[] args) {

String[][] name = {{"Mr.","Mrs.","Mis."},{"Melesew","Abebe"}};

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;

void show(int nn){


int[] id = new int[10];

15
Object Oriented Programming with Java book Prepared by: Melesew M.

String[] name = new String[10];


Scanner input = new Scanner(System.in);

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("===============================");
}

public static void main(String[] args) {


Main m = new Main();
Scanner input = new Scanner(System.in);
int n;
System.out.println("how many users are there ?");
n = input.nextInt();
m.show(n);
}
}

Advanced java example to demonstrate array of different types using loop


The following program demonstrates how to accept different type of data using array in java OOP.
package studentinfo;

import java.util.*;

public class studentinfo {

String studname,studid;

int studage;

void displaystudentinfo(String sname,String sid,int sage)

studname=sname;studid=sid;studage=sage;
System.out.println(studname+" "+ studid +" "+studage);

public static void main(String[] args) {

try{

16
Object Oriented Programming with Java book Prepared by: Melesew M.

Scanner get= new Scanner(System.in);

studentinfo studinfo=new studentinfo();

int[] arr = new int[100];

studentinfo stud[] = new studentinfo[arr.length];

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;

public class ArmstrongNumber {

public static void main(String[] args) {

System.out.println("Armstrong number is a number which


cubic root sum is equal to itself.");

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{

System.out.println(temp+" is not armstrong.");

// write a java program that determines a given number is palindrome or not.


package PalandromeNumber;

public class PalandromeNumber {

public static void main(String[] args) {

18
Object Oriented Programming with Java book Prepared by: Melesew M.

System.out.println("Palandrome number is a number that we can read


both side but no change.");

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){

System.out.println("===== "+temp+" is Palandrome ======");

}else{

System.out.println("==== "+temp+" is not Palandrome ===");

// write a java program that constructs Fibonacci serious?


package FabonaciSerious;

public class FabonaciSerious {

public static void main(String[] args) {

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 and Object


- Java is OOP.
- When problems are occurred we can design a solution using classes and objects.
- Object oriented design process involves 3 procedures:
 Divide the problem domain into types of objects or class.
 Model the relationship between classes.
 Model the attributes, method of each type.
 Class is a referenced data type.
 Combines data and method i.e. data method.
 Define a data type.
 Corresponds to concepts in the problem domain.
 Used to model problem.
 Used to reduce complexity.

 Class declaration

Access-modifier class className{


fields;
method(){
……
}
}

 Access modifiers are:- public, private, protected, default

 class :- keyword used to create class and must be small letter case.

 className:- Any legal name to assign class.

21
Object Oriented Programming with Java book Prepared by: Melesew M.

o Method contains:-

 Function (define):- it returns value & not define by class name.

 Procedure(define):-not return value.

 Constructor(define):-not return value.

 Same as class name

 Do not return a value

Example: a simple class declaration

class Circle{
double radius;
double findArea(){
return radius * radius;
}
}

// Example of class and object declaration

package studentinfo;

public class StudentInfo {


int id;
String name;

StudentInfo(int i, String n){


id=i;
name=n;
}

void show(){
System.out.println(id+" "+name);
}

public static void main(String[] args) {

StudentInfo s1 = new StudentInfo(12,"Hana");


StudentInfo s2 = new StudentInfo(13,"Melesew");

22
Object Oriented Programming with Java book Prepared by: Melesew M.

System.out.println("ID Name");
System.out.println("-------");
s1.show();
s2.show();
}
}

 Prototype: - used for class and object.

 The first step in problem solving process is identifying the problem.

Example 1: The following example show how class and object created correctly.

package StudentClass;

public class StudentClass {


String name;
int age;

void getName(String sname){


name=sname;
}

int getAge(int sage){


return age=sage;
} // Output

public static void main(String[] args) {

StudentClass stud = new StudentClass();


stud.getName("Abebe");
stud.getAge(25);

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

className objectName = new className();

 Instantiated object

o objectName = new className(arg.); // we can make also empty for default constructor

 To call an object

o objectName.identifierName;

 identifier name includes:-

o class name:-we can’t access by object

o method:- we can access by object

o variable name:-

Example: - This example demonstrates how to instantiate object(s) in a given class.

package EmployeeDetails;

public class EmployeeDetails {


String name;
String position;
double salary;

public EmployeeDetails(String n,String p,double s){


name=n;
position=p;
salary=s;
}

void display(){
System.out.println(name+" "+position+" "+salary);
}

public static void main(String[] args) {

EmployeeDetails ed1 = new EmployeeDetails("Melesew","Accountant",5000);


EmployeeDetails ed2 = new EmployeeDetails("Ayenew","Teacher",5600);

24
Object Oriented Programming with Java book Prepared by: Melesew M.

ed1.display();
ed2.display();
}
}
//Output

 Method can be defined like:

o Access modifier dataType(void,int,..) + method name;

 How to access class method----- with dot(.) operator

 Syntax: objectName.members of class

 Variables:

o Instance: - declared inside class.

o Local:- inside method, constructor, function

o Static: - are the same for all class

 Constructor

- A constructor is a special type of method that has the following property.


 A constructor with no parameter is referred to as a default constructor.
 Constructors must have the same name as the class itself.

25
Object Oriented Programming with Java book Prepared by: Melesew M.

 Constructors don’t have return type even void.


 Constructors are invoked using the new operator when an object is created.
 Constructors play the role of initializing objects.

 Two main types of constructor

i. Default(non-parameterized constructor)

ii. Parameterized constructor

Example: A constructor that calculates the area of a circle.

package Circle;

public class Circle { // Output


double radius;

Circle(double r){ // Constructor


radius=r;
}

Circle(){
radius=2;
}

public static void main(String[] args) {

Circle myCircle = new Circle();


System.out.println("radius = "+myCircle.radius);
Circle myCircle2 = new Circle(35);
System.out.println("radius = "+myCircle2.radius);
}
}

- Constructor name must be the same as class name or method name.


- Constructors always don’t have return type.

 Access modifiers (Level of scope visibility)


 public: - available anywhere.
 private: - available on the method that we are working on only.
 protected: - available on the package. Not used I class declaration but others can.
 default: - available to the class & package.

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

Fig.1: Access modifier access


acces level

Modifier Class Package Subclass World


Public   
Protected   
Default   X
Private  X X

// observe the following example to demonstrate


demons access modifiers in java NetBeans

output by changing access modifiers.


modifiers e.g1:

package AccessModifiers;

public class AccessModifiers {


private int d=10;

private void msg(){


System.out.println("Hello World");
}

public static void main(String[] args) {

AccessModifiers obj = new AccessModifiers();


System.out.println(obj.d); // can return a value by changing private to
obj.msg();
}
}

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;

public void setPrice(float newPrice){


price=newPrice;
}
}

class B{

public static void main(String[] args) {

AA x = new AA();
x.price=25f;

System.out.println(x.color);
System.out.println(x.price);
}
}

Important java keywords:

 this
 final
 static
 super

Example: The following exercise shows how class, variable as well as methods
can we construct/deploy.
package employee;

public class employee {


String name="";
String country="";

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) {

employee c = new employee("Melesew","Ethiopia");


employee d = new employee();
c.PrintInformation();
d.PrintInformation();
}

public void PrintInformation(){


System.out.println("My name is : "+name+" and I am from : "+country);
}
}

 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.

 We can create more than one constructor in a single class.

29
Object Oriented Programming with Java book Prepared by: Melesew M.

Default constructor

- If no constructor is declared java provides a parameter-less default constructor that


initializes each field to its default value.
 Default value
o Primitive numeric types and char=0;
o Boolean = false;
o All referenced type & string=null;
o Float = 0.0f;
o Double = 0.0d;

 How to create new object?

- 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);

Static keyword in java

 The static keyword in java is used for memory management.


 We can apply static keyword in:-
o Variable
o Method
o Blocks
o Nested classes
 The static keyword belongs to the class than instance of the class.

i. Java static variables


- If you declare any variable as static, it is known as static variables.
- The static variables can be used to refer the common property of all objects that is not
unique to each object.
- The advantages of static variable are makes solve program memory efficient.

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;

public class Counter {


int count=0; //if you add static keword befor int the output is changed 1 2 3

Counter(){
count++;
System.out.println(count);
}

public static void main(String[] args) {

Counter c1 = new Counter();


Counter c2 = new Counter();
Counter c3 = new Counter();
}
}

31
Object Oriented Programming with Java book Prepared by: Melesew M.

ii. Java static Methods

- 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;

public class Student {


int id;
String name;
static String college="Technology"; //static variable college

static void change(){ //static method change


college="CS";
}

Student(int i,String n){


id=i;
name=n;
}

void display(){
System.out.println(id+" "+name+" "+college);
}

public static void main(String[] args) {


Student.change();
// Student.college="FB";

Student s1 = new Student(12,"Abebe");


Student s2 = new Student(13,"Almaz");
Student s3 = new Student(14,"Kebede");

s1.display();
s2.display();
s3.display();
} }

32
Object Oriented Programming with Java book Prepared by: Melesew M.

Q. why java main method is static?

iii. Java static block

- It is used to initialize the static data members.

- It is executed before main method at the time of class loading.

e.g.

package A;

public class A {
static{
System.out.println("Static blok invoked.");
}

public static void main(String[] args) {

System.out.println("Hello World!");
}
}
o In static block we can output the data without main function i.e. by using static keyword.

“this” keyword in java

 this is a referenced variable that refers to the current object.

 this keyword can be used:

 To refer current class instance variable.

 this() can be used to invoke current class constructor.

 Used to invoke (call) current class method.

 Can be passed as an argument in the method call.

 To return the current class instance.

 Used for instance variables.

- If there is an ambiguity between instance variable and parameter(local variable) , so that

this keyword resolves the problem of ambiguity. Such as this.name=name;

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;

public class Student {


int id; // instance variable
String name; // instance variable

Student(){ //default constructor


System.out.println("default constructor is invoked.");
}

Student(int id, String name){


this(); //Calling of the above default constructor
this.id=id; //Calling of the above variable id
this.name=name; //Calling of the above variable name
}

void display(){
System.out.println(id+" "+name);
}

public static void main(String[] args) {

Student s1 = new Student(10,"Melesew");


Student s2 = new Student(20,"Ayenew");

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.*;

public class Student {

int id;

String name;

Student(){

System.out.println("================================");

System.out.println("default constructor is invoked.");

Student(int i, String n){ //Without the keyword this

this();

id=i;

name=n;

public void display(){

System.out.println("================================");

System.out.println("\t"+id+" "+name);

System.out.println("================================");

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

int a;

String b;

System.out.print("Enter ID number : ");

a=input.nextInt();

System.out.print("Enter Stud name : ");

b=input.next();

Student s1=new Student(a,b);

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

assigning a value to another variable with this keyword.

package Person;

public class Person {


int x;
int y;

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);
}

public static void main(String[] args) {


Person p = new Person();
p.msg(3, 4);
System.out.println(p.x+" "+p.y);
}
}

- this is used to differentiate local variables from instance variables.

- Used to access the current constructor.

Example: The following example describes how to use this keyword.

package Student;

public class Student {

36
Object Oriented Programming with Java book Prepared by: Melesew M.

int id;
String name;
String city;

Student(int id,String name){


this.id=id;
this.name=name;
}

Student(int id,String name,String city){


this(id,name); //this() used to call varibles outside its constructor
this.city=city;
}

void display(){
System.out.println(id+" "+name+" "+city);
}

public static void main(String[] args) {

Student s1 = new Student(12,"Belay","DMU");


Student s2 = new Student(13,"Ejigu","BDU");

s1.display();
s2.display();
}
}
- A class which has the same package are stored in the same folder.

- If we have static methods we didn’t need to declare an object.

e.g.
package Computer;

public class Computer {

static void show(){


System.out.println("default method.");
}

37
Object Oriented Programming with Java book Prepared by: Melesew M.

static void show(String n){


System.out.println("One argument");
}

public static void main(String[] args) {

show();
show("melesew");
}
}

- this keyword can be used to invoke current class method.

package A;

public class A {
void m(){
System.out.println("Method is invoked.");
}

void n(){
this.m();
}

void p(){
n();
}

public static void main(String[] args) {

A a1 = new A();
a1.p();
}
}

- Super used as a reference variable. Static keywords used to save memory.

- 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

Inheritance and polymorphism

i. Inheritance
- It is a mechanism in which one object acquires all the properties and behaviors of parent

object.

- It means to take something that is already made.

- Inheritance represents the “is-A” relationship also known as “parent-child” relationship.

 Why use inheritance?

o For method overriding (not overloading) so running polymorphism can be

achieved.

o For code reusability

 Syntax of inheritance

o Access modifier class subclassName extends superclassname{

//method(s) and field(s);

 Access modifier:- public, private, protected, etc

 class: - keyword used to create class.

 Sub class name: - can be any legal name.

 extends: - keyword used to inherit a functionality from super class.

 Super class name: - can be any legal name.

 The “extends” keyword indicates that you are making a new class that drives from

the existing class.

 In terminology of java:

o A class that is inherited is called a super class (parent class).

o The new class is called subclass (child class/ sub class).

39
Object Oriented Programming with Java book Prepared by: Melesew M.

o e.g. employee is super class of programmer

o e.g. programmer is sub class of employee

example1: the following program shows how inheritance is written in java

package Employee;

public class Employee { //Parent class


float salary=4000;
}

class Programmer extends Employee{ //child class inherits parent class


float bonus=1000;
}

class Test{

public static void main(String[] args) {

Programmer p = new Programmer();


System.out.println("Programmer salary is "+p.salary);
System.out.println("Programmer salary is "+p.bonus);
}
}

//Output

40
Object Oriented Programming with Java book Prepared by: Melesew M.

Types of inheritance

- On the base of class, there can be 3 types of inheritance.

 Single

 Multiple / multi-level

 Hierarchical

- In java programming multiple and hierarchical inheritance is supported through interface

only.

- Multiple and hybrid inheritance is not supported in java unless we have interface.

Q. why multiple inheritance is not supported in java?

- To refer complexity and simplify the language, multiple inheritance is not supported in java

but we can apply in interface.

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

public static void main(String[] args) {


C obj = new C();
obj.msg();
}
}

Aggregation in java

 If a class have an entity reference it is known as entity aggregation.

 Aggregation represents “HAS-A” relationship.

Why use aggregation?

Example: //

package Address;

public class Address {


String city,state,country;

42
Object Oriented Programming with Java book Prepared by: Melesew M.

public Address(String city,String state,String country){


this.city=city;
this.state=state;
this.country=country;
}
}

class emp{
int id;
String name;
Address ad;

public emp(int id,String name,Address ad){


this.id=id;
this.name=name;
this.ad=ad;
}

void display(){
System.out.println(id+" "+name+" "+ad.city+" "+ad.state+" "+ad.country);
}

public static void main(String[] args) {

Address ad1 = new Address("DMU","Amhara","Ethiopia");


Address ad2 = new Address("BDR","Amhara","Ethiopia");
emp e1 = new emp(12,"Belay",ad1);
emp e2 = new emp(13,"Hana",ad2);

e1.display();
e2.display();
}
}

//Output

43
Object Oriented Programming with Java book Prepared by: Melesew M.

Super keyword

- Used to call parent (main) class.

- It is a reference variable that is used to refer immediate parent class object.

Usage of super keyword:

- Used to refer immediate parent class instance variable.

- super() is used to invoke immediate parent class constructor.

- Used to invoke parent class method.

i. Super is used to refer immediate parent class instance variable

//example:

package Vecihle;

public class Vecihle {


int speed=50;
}

class Bike extends Vecihle{


int speed=100;

void display(){
System.out.println("Bike class speed : "+speed); //Without super() keyword
System.out.println("Vecihle class speed : "+super.speed); //With super() keyword
}

public static void main(String[] args) {


Bike b = new Bike();
b.display();
}
}

 The difference between super and this keyword in java:

o this used to call inside the method only.

o super used to call outside the method (main) class.

44
Object Oriented Programming with Java book Prepared by: Melesew M.

ii. Super is used to invoke parent class constructor.

//example:

package Vecihle;

public class Vecihle {

Vecihle(){
System.out.println("Vecihle is created.");
}
}

class Bike extends Vecihle{

Bike(){
super(); //used to invoke parent class constructor
System.out.println("Bike is created.");
}

public static void main(String[] args) {


Bike b = new Bike();
}
}
Note: -

- Private keyword used for mostly used in instance variables.

- Only accessible inside the method of the class in which they are declare.

iii. Super used to invoke parent class method.

 The super keyword used in case subclass contains same method name as parent class.

Example:

package Person;

public class Person {

void msg(){
System.out.println("Hello");

45
Object Oriented Programming with Java book Prepared by: Melesew M.

}
}

class Student extends Person{


void msg(){
System.out.println("Welcome to java");
}
void display(){
msg(); //Current or subclass method will be invoked
super.msg(); //Parent class method will be invoked
}

public static void main(String[] args) {


Student s = new Student();
s.display();
}
}

Final keyword

- The final keyword in java is used to restrict the user.

- The java final keyword can be used in:

 Variable

 Methods, and

 Class

- A final variable that has no value is called “blank final variable” or “uninitialized final variable”.

- It can be initialized in the constructor only.

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

- Java final keyword:-

 Stop value change

 Stop method overriding

 Stop inheritance

- Static also used together or alone in java.

- Syntax: Access modifier dataType identifierName = value;

i. Java final variable

- 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();
}
}

ii. Java final method

- If you made any method as final, you can’t override it.

//example

pckage Bike;

public class Bike {

final void run(){


System.out.println("Hello");
}
}

47
Object Oriented Programming with Java book Prepared by: Melesew M.

class Handa extends Bike{

void run(){ //error displayed because final method can't be override


System.out.println("Hello from Handa class");
}

public static void main(String[] args) {

Handa h = new Handa();


h.run();
}
}

iii. Java final class

- If you make any class as final, you can’t extend (inherit) it.

//example

package Bike;

public final class 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");
}

public static void main(String[] args) {


Handa h = new Handa();
h.run();
}
}

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

name in the same class.

- There are 2 kinds of polymorphism:-

 Overloading (Method)

o Two or more methods with different signature.

o The same name with different kind of data.

 e.g. println(int), println(double), println(String)

//example

package Test;

public class Test {

public static void main(String[] args) {

myPrint(5);
myPrint(5,3);
}

//example of method Overloading

static void myPrint(int num1){


System.out.println("num1 = "+num1);
}

static void myPrint(int x,int y){


System.out.println("num1 = "+x+" and num2 = "+y);
}
}

//Output

 Overriding (Method)

49
Object Oriented Programming with Java book Prepared by: Melesew M.

o Placing on inherited method with another having the same signature.

o Overriding method a subclass that exists in the super class.

Example:

package MethodOverwrite;

import java.util.*;

public class Main {


private String firstName="";
private String lastName=null;
private int age;
private static double salary=5000.00;

//default constructor
public Main(){
System.out.println("default constructor is invoked");
}

void display(String fn, String ln, int a){


firstName=fn;
lastName=ln;
age=a;
System.out.println("Fullname : "+firstName+" "+lastName+" Age : "+age+" Salary : "+salary);
}

void display(String sex){


sex=sex;
System.out.println("Sex : "+sex);
}

public static void main(String[] args) {

Scanner in = new Scanner(System.in);


System.out.print("Enter your gender : ");
String gender = in.next();
Main m = new Main(); //default constructor is invoked
m.display("Melesew","Mossie",24);

50
Object Oriented Programming with Java book Prepared by: Melesew M.

m.display(gender);
}
}

//Output

How to override a method?

 Create a method in a sub class having the same signature as a method in super class.

 The return type must be the same also in method overriding.

 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

 Abstraction means data hiding by hiding implementation & show interface.

o e.g. access modifier abstract class className{

abstract method();

 here,

o access modifiers:- public, private, protected

o abstract:- keyword used to create abstract class & method

o class:- keyword used to create a class

o class name:- can be any legal identifier

 abstract can be:-

51
Object Oriented Programming with Java book Prepared by: Melesew M.

o Abstract class: - can contain either abstract or non-abstract method & have body.

o Abstract method: - Method without body.

e.g. public abstract class className{

abstract method();
}
 Non-abstract method has body.

e.g.

public abstract class Test{


public abstract void msg();
public void show(){
System.out.println(“Hello”);
}
}
Public class x extends Test{
Public void msg(){
System.out.println(“From Abstract Method”);
}
 It is impossible to execute abstract method without abstract class.

 Use abstraction and interface method.

 It is the process of hiding the implementation details and showing only functionality to

the user (i.e. interface)

Abstract class

- A class with abstract keyword – is known as abstract class.

- It can have abstract and non-abstract method.

- It can never instantiated. (we can’t create object)

- A class can’t be both abstract and final

 Final classes can’t be extended.

- If a class contains abstract method the class must be abstract.

52
Object Oriented Programming with Java book Prepared by: Melesew M.

- Abstract class contains instance variables.

Abstract Method

- It is a method declared without any implementation (body).

- The method body is provided in the subclass.

- Abstract method can never be final and abstract.

- Any class that extends an abstract class must implement all the abstract methods of the

super class unless a subclass is also on abstract class.

//example:

public abstract class Test{

abstract void msg();

public class x extends Test{

void msg();

- A sub class may also abstract class.

e.g.

package Test;

public abstract class Test {

public abstract void m();

abstract class B extends Test{

abstract void msg();

class C extends B{

53
Object Oriented Programming with Java book Prepared by: Melesew M.

void msg(){

System.out.println("Abstract class method body is provided in subclass");

public void m(){

System.out.println("Hello");

void n(){

System.out.println("World.");

public static void main(String[] args) {

C c = new C();

c.msg();

c.m();

c.n();

//Output

Interface

 It is a blue print of a class.

 It has static constants (as data member) and abstract method (as a method) only.

 It is a mechanism to achieve full abstraction.

 Like abstract class it can’t be instantiated.

 Java compiler adds public and abstract keyword before the interface method.

o Adds public, static & final keyword before 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();

 It is converted at runtime like follows:

interface printable{

public static final int MIN=5;

public abstract void print();

Example2:

package Printable;

interface Printable {

void print();

class A implements Printable{

public void print(){

System.out.println("Hello");

public static void main(String[] args) {

55
Object Oriented Programming with Java book Prepared by: Melesew M.

A obj = new A();

obj.print();

Example 3:

package Showable;

interface Showable {
abstract void show();
}

interface Printable {
abstract void print();
}

class B implements Showable,Printable{

public void show(){


System.out.println("Welcome to Showable");
}

public void print(){


System.out.println("Welcome to Printable");
}

public static void main(String[] args) {


B ob = new B();
ob.show();
ob.print();
}
}
- One interface with another interface can’t be inherited rather it can implemented it.

Java package

56
Object Oriented Programming with Java book Prepared by: Melesew M.

- Used to make the class categorize.

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

You might also like