Object Oriented Concepts and Examples
Object Oriented Concepts and Examples
Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies the software development and
maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
An entity that has state and behavior is known as an object e.g. chair, bike, marker,
pen, table, car etc. It can be physical or logical (tangible and intangible). The example of
an intangible object is the banking system.
For Example, Pen is an object. Its name is BIC; color is white, known as its state. It is
used to write, so writing is its behavior.
Object Definitions:
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.
Advantage of Method
o Code Reusability
o Code Optimization
We can have multiple classes in different java files or single java file. If you define
multiple classes in a single java source file, it is a good idea to save the file name with
the class name which has main() method.
File: TestStudent1.java
//another class
//Creating Student class.
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
1. By reference variable
2. By method
3. By constructor
We can also create multiple objects and store information in it through reference
variable.
File: TestStudent3.java
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}
File: TestStudent4.java
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
File: TestEmployee.java
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display(); } }
1) Object and Class Example: Initialization through
reference
Initializing an object means storing data into the object. Let's see a simple example
where we are going to initialize the object through a reference variable.
File: TestStudent2.java
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
File: TestRectangle1.java
class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle1{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
o By new keyword
o By newInstance() method
o By clone() method
o By deserialization
o By factory method etc.
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the object is created, and memory is allocated for the object.
Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java compiler
creates a default constructor if your class doesn't have any.
Note: We can use access modifiers while declaring a constructor. It controls the object
creation. In other words, we can have private, protected, public or default constructor in
Java.
In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.
The default constructor is used to provide the default values to the object like 0, null,
etc., depending on the type.
Explanation:In the above class,you are not creating any constructor so compiler
provides you a default constructor. Here 0 and null values are provided by default
constructor.
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.
The parameterized constructor is used to provide different values to the distinct objects.
However, you can provide the same values also.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in
the list and their types.
Output:
111 Karan 0
222 Aryan 25
this keyword in java
There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.
Suggestion: If you are beginner to java, lookup only three usage of this keyword.
`
this: to refer current class instance variable
The this keyword can be used to refer current class instance variable. If there is
ambiguity between the instance variables and parameters, this keyword resolves the
problem of ambiguity.
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same.
So, we are using this keyword to distinguish local variable and instance variable.
Output:
In OOP, computer programs are designed in such a way where everything is an object
that interact with one another. Inheritance is one such concept where the properties
of one class can be inherited by the other. It helps to reuse the code and establish a
relationship between different classes.
1. Single Inheritance:
In single inheritance, one class inherits the properties of another. It enables a derived
class to inherit the properties and behavior from a single parent class. This will in turn
enable code reusability as well as add new features to the existing code.
Here, Class A is your parent class and Class B is your child class which inherits the
properties and behavior of the parent class.
4 }
5 Class B extends A {
---
6
}
7
2. Multilevel Inheritance:
5 ---
6 }
Class C extends B{
7
---
8
}
9
3. Hierarchical Inheritance:
If we talk about the flowchart, Class B and C are the child classes which are inheriting
from the parent class i.e Class A.
Class A{
---
Class B extends A{
---
Class C extends A{
---
4. Hybrid Inheritance:
If we talk about the flowchart, class A is a parent class for class B and C, whereas
Class B and C are the parent class of D which is the only child class of B and C.
Now we have learned about inheritance and their different types. Let’s switch to
another object oriented programming concept i.e Encapsulation.
The syntax of Java Inheritance
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and
the new class is called child or subclass.
Object Oriented Programming : Encapsulation
Encapsulation is a mechanism where you bind your data and code together as a single
unit. It also means to hide your data in order to make it safe from any
modification. What does this mean? The best way to understand encapsulation is to
look at the example of a medical capsule, where the drug is always safe inside the
capsule. Similarly, through encapsulation the methods and variables of a class are
well hidden and safe.
return name;
this.name = name;
OUTPUT
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}
Output:
barking...
eating...
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}
Output:
weeping...
barking...
eating...
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}
Output:
meowing...
eating...
Let us try to understand the above code. I have created a class Employee which has
a private variable name. We have then created a getter/accessor and setter/mutator
methods through which we can get and set the name of an employee. Through these
methods, any class which wishes to access the name variable has to do it using these
getter and setter methods.
Let’s move forward to our third Object-oriented programming concept i.e. Abstraction.
Abstraction refers to the quality of dealing with ideas rather than events. It basically
deals with hiding the details and showing the essential things to the user. If you look
at the image here, whenever we get a call, we get an option to either pick it up or just
reject it. But in reality, there is a lot of code that runs in the background. So you don’t
know the internal processing of how a call is generated, that’s the beauty of
abstraction. Therefore, abstraction helps to reduce complexity. You can achieve
abstraction in two ways:
a) Abstract Class
b) Interface
Abstract class: Abstract class in Java contains the ‘abstract’ keyword. Now what does
the abstract keyword mean? If a class is declared abstract, it cannot be instantiated,
which means you cannot create an object of an abstract class. Also, an abstract class
can contain abstract as well as concrete methods.
Note: You can achieve 0-100% abstraction using abstract class.
To use an abstract class, you have to inherit it from another class where you have to
provide implementations for the abstract methods there itself, else it will also become
an abstract class.
These methods need be present for every car, right? But their working is going to be
different.
Let’s say you are working with manual car, there you have to increment the gear one
by one, but if you are working with an automatic car, that time your system decides
how to change gear with respect to speed. Therefore, not all my subclasses have the
same logic written for change gear. The same case is for speedup, now let’s say when
you press an accelerator, it speeds up at the rate of 10kms or 15kms. But suppose,
someone else is driving a super car, where it increment by 30kms or 50kms. Again
the logic varies. Similarly for applybrakes, where one person may have powerful
brakes, other may not.
Since all the functionalities are common with all my subclasses, I have created an
interface ‘ParentCar’ where all the functions are present. After that, I will create a
child class which implements this interface, where the definition to all these method
varies.
Next, let’s look into the functionality as to how you can implement this interface.
So to implement this interface, the name of your class would change to any particular
brand of a Car, let’s say I’ll take an “Audi”. To implement the class interface, I will
use the ‘implement’ keyword as seen below:
public class Audi implements ParentCar {
int speed=0;
int gear=1;
public void changeGear( int value){
gear=value;
}
public void speedUp( int increment)
{
speed=speed+increment;
}
public void applyBrakes(int decrement)
{
speed=speed-decrement;
}
void printStates(){
System.out.println("speed:"+speed+"gear:"+gear);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Audi A6= new Audi();
A6.speedUp(50);
A6.printStates();
A6.changeGear(4);
A6.SpeedUp(100);
A6.printStates();
}
}
Here as you can see, I have provided functionalities to the different methods I have
declared in my interface class. Implementing an interface allows a class to become
more formal about the behavior it promises to provide. You can create another class
as well, say for example BMW class which can inherit the same interface ‘car’ with
different functionalities.
Polymorphism means taking many forms, where ‘poly’ means many and ‘morph’
means forms. It is the ability of a variable, function or object to take on multiple
forms. In other words, polymorphism allows you define one interface or method and
have multiple implementations.
Let’s understand this by taking a real-life example and how this concept fits into Object
oriented programming.
Let’s consider this real world scenario in cricket, we know that there are different types
of bowlers i.e. Fast bowlers, Medium pace bowlers and spinners. As you can see in the
above figure, there is a parent class-BowlerClass and it has three child
classes: FastPacer, MediumPacer and Spinner. Bowler class
hasbowlingMethod() where all the child classes are inheriting this method. As we
all know that a fast bowler will going to bowl differently as compared to medium pacer
and spinner in terms of bowling speed, long run up and way of bowling, etc. Similarly
a medium pacer’s implementation of bowlingMethod() is also going to be different
as compared to other bowlers. And same happens with spinner class.
The point of above discussion is simply that a same name tends to multiple forms. All
the three classes above inherited the bowlingMethod() but their implementation is
totally different from one another.
Let us look at the following code to understand how the method overloading works:
class Adder {
Static int add(int a, int b)
{
return a+b;
}
static double add( double a, double b)
{
return a+b;
}
If we have to perform only one operation, having same name of the methods increases the readability o
Suppose you have to perform addition of the given numbers but there can be any number of arguments
method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be diff
other programmers to understand the behavior of the method because its name differs.
In this example, we are creating static methods so that we don't need to create instance for calling met
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
Output:
22
33
In other words, If a subclass provides the specific implementation of the method that has been declared
class, it is known as method overriding.
Output:
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
All the classes, interfaces, packages, methods and fields of java programming language
are given according to java naming convention.
Name Convention
class name should start with uppercase letter and be a noun e.g. String, Color, Button, Sys
etc.
interface name should start with uppercase letter and be an adjective e.g. Runnable, Remote,
etc.
method name should start with lowercase letter and be a verb e.g. actionPerformed(), main()
println() etc.
variable name should start with lowercase letter e.g. firstName, orderNumber etc.
package name should be in lowercase letter e.g. java, lang, sql, util etc.
If name is combined with two words, second word will start with uppercase letter always
e.g. actionPerformed(), firstName, ActionEvent, ActionListener etc.