Category Archives: OOP

Java Tut – Abstraction

In OOP abstraction is a process of hiding the implementation details from the use, only the functionality will be provided to the user.In other words user will have the information on what the object does instead of how it does it.

In java abstraction is achieved using abstract classes, and interfaces.
Abstract Class:
A class which contains the abstract keyword in its declaration is known as abstract class.

– Abstract classes may or may not contain abstract methods ie. methods with out body( public void get(); )

– But if a class have at least one abstract method,then the class must be declared abstract

– If a class is declared abstract it cannot be instantiated
– To use an abstract class you have to inherit it from another class, provide implementations to the abstract methods in it.
– If you inherit an abstract class you have to provide implementations o all abstract methods in it


and from another class

It will show error because of abstract class:

Abstract Method:

Declaring a method as abstract has two consequences:

  • The class containing it must be declared as abstract.
  • Any class inheriting the current class must either override the abstract method or declare itself as abstract.

Eventually a descendant class has to implement the abstract method; otherwise you would have a hierarchy of abstract classes that cannot be instatiated.

Suppose salary class is inherits the Employee class, then it should implement the computePay() method as shwon below:
//will add the code later


Java Tut – Polymorphism

Polymorphism the most common use of OOP occurs when a parent class reference is used to refer to a child class object.
Any Java object that can pass more than one IS-A test is considered to be polymorphic.In java all java objects are polymorphic since any object will pass the IS-A test for their own type and for the class object.
It is important to know that only possible way to access an object is through a reference variable.A reference varibale can only be one type.Once declared, the type of a reference variable cannot be changed.

A reference variable can be declared as a class or interface type

Let us look an example

Now the Deer class is considered to be polymorphic since this has multiple inheritance.Following are true for the above example:

Virtual Methods:
In this section,I will show you how the behavious of overriden methods in java allows you to take advantage of poly




Java Tut – Method Overriding

If subclass has the same method s declared in the parent class, it is known as method overriding in java.

– Method override is used for runtime polymorphism
– Method overriding is used to provide specific implementation of a method that is already provided by its super class.

Rules –
1.Method must have same name is in the parent class
2. method must have separator as in the parent class
3. Must be IS-A relationshp

understanding the problem without method overriding:


Problem is that I have to provide a specific implementation of run() method in subclass that is why we use method overriding.

Example of method overriding:

May be I did some wrong so output is not coming

Another example :
Java method overriding example of bank



Java Tut – inheritance

The classs which inherits the properties of other is known as subclass(derived class,child class etc.) and the class whose properties are inherited is known as superclass(base class,parent class).

extends keyword:
extends is the keyword used to inherit the properties of a class, below given is the syntax of extends keyword:



Super keyword:
The super keyword is similar to this keyword, following are the scenarios where the super keyword is used

– it is ised to differentiate the members of superclass from the members of subclass, if they have same names,
– It is used to invoke the superclass contructor from subclass
Differentiating the members:


Invoking Superclass constructor

If you want to call a parametrized constructor of the super class, you need to use the super keyword as shown below:

Sample code:


IS-A Relationship:
IS-A is a new way of saying: This object is a type of that object.Let us see how the extends keyword is used to achieve inheritance.

In object oriented terms, the following are true-
Animal is the superclass of Mammal class .
Animal is the superclass of Reptile class
Mammal and Reptile are subclass of Animal class
Dog is the subclass of both Mammal and ANimal classes
Now  if we consider the IS-A relationship,,,we can say-
-Mammal IS-A Animal
-Reptile IS-A Animal
-Dog IS-A Mammal
Hence: Dog IS-A Animal as well

Using the extends keyword the subclasses will inherit all the properties of super class except the private properties.

Now, we can ensure that Mammal is actually an Animal with the use of the instance operator.


Since we have a good understanding of the extends keyword let us look into how the implements keyword is used to get the IS-A relationship.

Genrally the implements keyword s used with classes to inherit the properties of an inheritance.Interfaces can never be extended by a class.

The instanceof keyword:

Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog is actually an Animal


Though there is some error in my above code.

HAS-A Relationship
These relationships are mainly based on the usage.This determines whether a certain class HAS-A certain thing.This relationship help to reduce duplication of codes as well as bugs.

let us look into an exampel:


More details in the link below.
Types of inheritance:
Java Tutorial

And one thing is Multiple Inheritance is not supported in java.It is illegal below:




Java Tut – Nested or Inner Class


1) Nested classes represents a special type of relationship that it can access all the members(data members and methods) of outer class including private
2) Nested classes are used to deelop more readable and maintainable code because it logically group classes and interfaces in one place only.
3)Code optimization:It requires less code to write.

Types of Nested classes:
1. Non-static nested class(inner class)
a) Member inner class
b) Anonymouse inner class
c)Local inner class
2. Static nested class

Non static nested class is known as inner class

Java member inner class:


Java Anonymous Inner Class
A class that have no name is known as anonymous inner class in java.It should be used if you have to override method of class or interface. Java anonymou inner class can be created by two ways:
1.Class(may be abstract or concrete)
2. Interface

Java anonymlus inner class example using class

Internal working of given code:

1. A class is created but its name is decided by the compiler which extends the Person class and provides the implementation of the eat() method.
2. An object of anonymous class is created that is referred by p reference variable of Person type.

Internal class generated by the compiler:

Local inner class:
A class created inside a method is called local inner class in java.If you want to invoke the methods of local inner class, you must instantiate this class inside the method.

Static nested class example with instance method:

Java Nested Interface:
syntax of nested interface which is declared within the interface

Syntax of nested interface which is declared within the class


Difference Between Method Overloading and Method Overriding in Java

Method Overloading:
1) Performed within class
2) Parameters must be different
3)Is the example of compile time polymorphism
4)Return type can be the same or different in method overloading.But you must have to change the parameter.
Method Overriding:
1)Method overriding occurs in two classes that have IS-A(inheritance) relationship
2)Parameters must be the same
3) Is the example of run time polymorphism.
4) Return type must be the same or covariant in method overriding

Overloading Example:


Overriding Example:

Java Tut – Exception Handling

The exeption handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained

In here we learn
What is exception: From dictionary: Exception is a n abnormal condition.
In java, exception is an event that disrupt he flow of the program.It is an object which is thrown at runtime.

What is exception handling. Exception handling is a mechanism to handle runtimer errors such as ClassNotFound,IO,SQL,Remote etc.

The core advantage of excepion handling is to maintain the normal flow of the application.Exception normally disruts the normal flow of the application that is wh we use exception handling:
Let take the scenario:
1) Checked Exception: e.g: IOException,SQLException
The classes that extend throwable class except RuntimeException and Error are known as checked exceptions.Checked exceptiions are checked at compile time.

2} Unchecked exceptions: The classes that extend RuntimeExceptiona re known as unchecked exceptions e.g: ArithmeticException,NullPointerException,ArrayIndexOutOfBoundsException etc. Uncheked exceptions are not checked at compile time rather checked at run time.

3)Error: Error is irrecoverable e.g:OutOfMemoryError, VirtualMachineError, VirtualMachineError, AssertionError etc.

Java exception handliung keywords:

2. catch
3. finally
4. throw
5. throws

1) Scenario where ArithemeticException occurs::

2) Scenario where NullPointerException occurs

3) Scenario where NumberFormatException occurs:
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException

4)Scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, It would result ArrayIndexOutOfBoundsException as shown below:

throw vs throws:
Throw: You cannot throw multiple exceptions.
Throws: You can declare multiple exceptions e.g: public void method() throws IOException,SQLException etc.

Java throw example:

Java throws example:

Java throw and throws example:

for further learning you can check out this link for reference:

Java Date & Time and Regex

Java provides he Date class available in java.util.*; packages, this class encapsulates the current date & time.

contructors: Date() , Date(long millisec)
boolean after(Date date)
int compareTo(Date date)
boolean equals(Object date)

Java Regex
Will work on regex later but it use java.util.regex package for pattern matching with regular expressions

Java Arrays

Java Arrays:

Creating Arrays:

The array elements are accessed throughthe index.Array indices are 0 based; that is, they start from 0 to arrayRefVar.length-1
double[] myList=new double[10];


foreach loops


Passing Arrays to Methods:

Returning an Array from a method:

The array class:

java.util.arrays for soritng and searching arrays,comparing and filling arrays.
public static int binarySearch(Object[] a,Object key)

public static boolean equals(long[] a1,long[] a2)

public static void fill(int[] a,int val)

public static void sort(Object[] a)

Java – String, String Buffer and String Builder Classes

Creating strings:


output: hello
public StringBuffer append append(String s)
public stringBuffer append(boolean b)
public StringBuffer append(char c)
replace(),delete(), reverse(),capacity(),length(),setCharAt(int index,char ch),setLength(),String subString(int start),String subString(int start,int end)

one example in buffer class:

length() and capacity() method


For more example:
I will see in future
– Java the complete reference(Best examples here)
– Oracle Java Library
– Android Reference
– Tutorials point for explanation


Java Tut – Character Class

Some escape sequence here :


The character class offers a number of useful class(i.e: static) methods for manipulating characters.You can create character object with the Character constructoir:

we normally use primitive though:
char ch=’a’;
Unicode for uppercase greek omega letter
char cunicode=’\u039A’;
char c=’test(‘x’);
Character methods:
Here is the list of the important intance  methods taht all subclasses of t

the character class implement
those are available in java.lang
Character Class isLetter(“c”),isDigit(“5”),

String toString(char ch)
ch — primitve character type
the method returns a string object representing the speciifed character value, that is, a one character string.


Java Tut – Numbers

Normally when we work with numbers, we use primitive data types such as byte,int,long,double, etc

int i=400;
float gpa=13.65;
byte mask=0xaf;
In develoment we need to use objects instead of primitive data types.So java provides wrapper classes

All the weapper classes are the subclasses of the abstract class Number.
Number Subclasses
The object of the wrapper class contains or wraps it respective primitive data type.converting primitive data types into object called boxing, and this is taken care by the while passing the wrapper class you just need to pass the value of the primitive data type to the constructor of the wrapper class.

And the wrapper object will be converted back to a primitive data type and this process is called un boxing.The Number class is part of the java.lang package.


When x is assigned integer value the compiler boxes the integer because x is integer object.Later, x is unboxed so that they can be added as integer.
Number Methods:
Here is the list of the instance methods that all the subclasses of teh Number class implement:

xxxxValue() method:
here is a separate method for each primitive data type:



compareTo() method:
Two different types cannot be compared, both the argument and the Number object invoking(ডাকা) should be the same type:

referenceName – this could be a Byte,Double,Integer,Float,Long or Short
Return Value:
– If the integer in referenceName is equal to argument object then 0 is returned.
– If the Integer is less than the argument than 1 is returned.
– If the Integer is greater than the argument than -1 is returned



equals() Method:
public boolean equals(Object o)
Here is the detail of parameters:
o — is any object
Return Value:
The method returns True or false if the arguments is not null and is an object of the same type and with the same numeric value.There are some extra requirements for Double and Float objects that are described in the Java API documentation.



Java Max() method:
The method gives the maximum of the two arguments.The arguments can be int,float,long,double
This method has following variants:

Parameters: This method accepts any primitive data type as parameter
Return value: This method returns the maximum of the two arguments



double exp(double d)




Parameter: d  a double data type
Return value: This method returns a double value


floor() method/ceil method:

This method floor gives the largest integer that is less than or equal to the argument.

This method ceil gives the smallest integer that is greater than or equal to the argument.

Parameter:A double or flaot primitive data type
Return Value: This method returns the largest integer that is less than or equal to the argument.Returned as double.


toString() method:

This method is used to get a string object representing the value of the number object.

If the method takes a primitive data type as an argument, then the String object representing the primitive data type value is returned.

If the method takes two arguments,then a String representation of the first argument in the radix specified by the second argument will be returned.

i — An int for which string representation would be returned



parseInt() or parseXXXX():

This method is used to get the primitive data type of a certain String.parseXXX() is a static method can have one argument or two.

s — This is a string representation of deciaml
radix – This would be used to convert String s into integer

Return Value:
parseInt(String s): This returns an integer(decimal only)
parseInt(int i): This returns an Integer, given a string representation of decimal,binary,octal or hexadecimal(radix equals 10,2,8 or 16 respectively) numbers as input.

Java Tut – Decision Making

If statement:



If-else statement:



if..else if…else statement:



nested if statement in java:
It is alwys legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statements.

we can also nest else if…else in the similar way as we have nested the if statement


Switch statements in Java
A switch statement allows a variable to be tested for equality against a list of values.Each value is called a case and the variable being switched on is checked for each case.




The ? : Operator
it is known as conditional operator in some previous post i have shown it.It can repalce the if…else statements.

where exp1,exp2 and exp3 are expressions, initially exp1 is evaluated,
– If the value of exp1 is true, then the vaue of exp2 will be the value whole expression
– If the value exp1 is false, then exp3 is evaluated and its value becomes the value of the entire expression.

Java Tut – Loop

Java programming language provides the following types of loop to handle looping requirements.Click on the following links to check the detail.
While Loop:
Syntax for while loop:



For Loop:
Syntax for for loop is:
the update statement can be left blank with a semicolon at the end.
example :


do..while loop:




Loop Control Statements:
break statements:


continue statements:

– In a for loop, the continue keyword causes control to immediately jump to the update statement.

– In a while loop or do-while loop, control immediately jumps to the boolean expression.



Enhanced for loop in Java:
it included from Java 5, the enhanced for loop was introduced.This is mainly used to traverse collection of elements including arrays.

Declaration: The newly declared block variable, which is a type compatible with the elements of the array you are accessing.

Expression: This evaluates to the array you need to loop through.The expression can be an array variable or method call that returns an array.



Java Tut – Operators

Arithmetic operator – Just like other languages
+,-,*,%,/++,– etc.

Relational Operators: ==,!=,>,<,>=,<= etc.

Bitwise Operators: Java defines several bitwise operators,which can be pplied to the integer types,long,int,short,char, and byte

Bitwise operator works on bits and performs bit-by-bit operation.
Assume if a=60 and b=13; now in binary format they will be a s follows:
Some operators:
& bitwise and, | bitwise inclusive or,^ bitwise exclusive XOR,~ bitwise compliment,<< left shift,>> right shift,>>> zero fill right shift

Logical Operators:
&& logical AND,|| logical OR,! logical NOT
assume boolean variable a holds true,b holds false.

Assignment Operator:

= simple assignment operator, += Ass and assignment operator c+=a is equivalent to c=c+a,-=,*=,/=,&=,%=,<<=,>>=,^=,|=

Conditional Operator/ternary operator:
variable x= (expression)?value if true:value if false

Instance of operator:
This  operator is used only for object reference variables.The operator checks whether the object is of particular type(class type or interface type).instance of operator is written as:



another example will still return true if the object being compared is the assignment compatible with the type on th right.