OOPs Concepts with Examples in Java

oops concepts with examplesObject Oriented Programming (OOP) is a programming concept used in several modern programming languages, like C++, Java and Python. Before Object Oriented Programming  programs were viewed as procedures that accepted data and produced an output. There was little emphasis given on the data that went into those programs. Object Oriented Programming works on the principle that objects are the most important part of your program. Manipulating these objects to get results is the goal of Object Oriented Programming. If you’re new to Java, you may want to start by taking this beginners course on Java.

Object Oriented Programming Concepts

OOP revolves around objects. You create the objects that you need and then create methods to handle those objects. These methods don’t influence the state of the objects, but it’s the other way around. Object Oriented Programming also addresses several other weaknesses of the other programming techniques (unstructured, procedural and modular).

A class (a blueprint that forms an object) can, for example, “inherit” the traits of another class, unlike modules. This means that your new class can do what your old class could, and more. There can be several given instances of a class at one time in a program, too.

In OOP, the data is grouped together with the methods that operate upon it, which makes it easy to maintain the integrity of the data and provide a structure to the program. To understand OOP better, you have to understand its concepts, or the foundation, it operates upon, which we’ll be explaining in this tutorial. It’s also a good idea to take a look at the other types of programming techniques and their weaknesses to get a better idea of how OOP differs from those techniques. Alternatively, you could just take our introductory course on Java -we teach you everything you need to know about OOP in our courses.

So what is an object oriented program exactly? It is a program that contains objects, of course, which have certain properties and have methods linked to them. You use these methods to obtain a programming result. Here are the basic object oriented concepts, with examples for each concept.

A Programming Object

When you’re creating an object oriented program, your perspective changes so that you view the world as a collection of objects. A flower is a good example of an object. The length of its stem, the color of its petals, its fragrance and its design are the properties or the attributes of the flower object. These attributes form the data in our program. The values that these attributes take (the blue color of the petals, for example) form the state of the object. What is the task of a flower? You could say it pollenates to produce new flowers. This is a method of the flower object.

An object is both the data and the function(s), or method, which operates on the data. An object can also be defined as an instance of a class, and there can be more than one instance of an object in a program.

How do you create an object in Java? Like this, using the new keyword:

Flower rose = new Flower;

This will create an object called rose in your program.

Class

When you want to create an object, you create its class first. A class will define the attributes as well as the methods of an object. A class can be used to create similar objects. You can think of a class as a blueprint of an object. If you had a class called “cars”, for example, it could have objects like Mercedes, BMW and Porsche. The properties defined by the class could be speed or the price of these cars, while the methods could be the tasks you could perform with these cars: race, for example.

How would you define a class in Java? Take a look at the example below:

public class Flower {
String name;
String color;
void pollination() {
}
}

Here, we created a class called Flower, with attributes name and color and a method called pollination. This is pretty similar in C++. If you’d like to quickly learn the C++ equivalent, check out this 1-hour C++ course.

Inheritance

Classes can share, obtain or “inherit” properties and methods that belong to existing classes. This lets you reuse existing code and reduces the time you spend coding. A class that inherits from another is called a derived class or a child class. A class that shares its properties and methods is called a base class or parent class. A base class can have additional properties and methods not present in the parent class that distinguishes it and provides additional functionality.

If you want a real world example, consider the Windows operating system. Windows 98 had certain properties and methods that were used in Windows XP. Windows XP was derived from Windows 98, but it was still different from it. Windows 7 was derived from Windows XP, but they were both different. They both followed a certain basic template and shared properties, however. This is true for base classes and derived classes too.

In Java, you can inherit a class using the extends keyword:

public class Flower {
String name;
String color;
void pollination() {
}
}
public class Rose extends Flower {
}

The inherited class Rose can now share the attributes and methods of the class Flower. For more info on declaring objects or classes in Java , you can see this course on Java fundamentals.

Polymorphism

Polymorphism refers to the ability of a method to be used in different ways, that is, it can take different forms at different times (poly + morphos). There are two types of polymorphism: compile time polymorphism and run time polymorphism.

Compile time (static) polymorphism occurs when a method is overloaded; that is, when the argument used with the method is changed. This is done to obtain different results. An example of this would be suggesting different names for being the President of a country, which would get you different results each time – but they would still be called the President.

Run time (dynamic) polymorphism occurs when the methods itself are changed. When you don’t need a President but a Prime Minister, you would have to override the existing method.

We’ll explain the concept with a simple example. Suppose you wanted to multiply two numbers together:

public int mulNum (int x, int y) {
//
}

But what if you had other numbers to multiple, but they had “double” values instead of “int” values? You would just change the argument:

public int mulNum (double x, double y) {
//
}

All you’ve done here is change the signature of the method – the name of the method remains the same. JVM (and other OOP compilers) can differentiate between methods and provide the right result depending on the input you give to them. Learn how polymorphism is handled in C++ with this course.

Data Abstraction

Data abstraction refers to the process of only displaying relevant properties and methods to handle an object, while hiding the rest. Data abstraction lets you reduce the complexity (apparently) of a program and is a large advantage offered by classes in OOP languages.

An example would help you understand this better. You can operate your phone as long as you have a keypad and a screen. You don’t to know about its micro circuitry, antenna, software or other technology to operate it. Its complexity is hidden.

You can declare a class as abstract in Java to use the data abstraction functionality. Once a class has been declared as abstract, however, it cannot be instantiated. The class doesn’t become useless- if it has any methods and fields, they can still be accessed. However, it’s impossible to declare an instance of the abstract class. They can be sub-classed.

You can create an abstract class using the abstract keyword. An abstract class may or may or may not contain abstract methods. A class containing abstract methods must be declared abstract – a normal class cannot contain abstract methods.

Here’s an example of how you can declare an abstract class in Java:

public abstract class ExampleAbs {
// declare your fields
// declare normal methods
}

Here’s an example of an abstract method declared within an abstract class in Java:

public abstract class ExampleAbs {
// declare your fields
abstract void delay();
}

The method delay() is the abstract method. Notice that its declaration is different from other method declarations – you don’t have to use curly braces after it. Also, you have to use a semicolon “;” after the declaration. An abstract method can exist side by side with non abstract methods. If you’d like to see the equivalent in C++, this course talks more about data abstraction in C++.

Encapsulation

Encapsulation refers to keeping objects with their methods in one place. It also protects the integrity of the data – prevents it from being needlessly altered by restricting access to the data, preferably by hiding it from outside elements. Encapsulation is often confused with data abstraction, but they are different concepts entirely. Data hiding, or data abstraction, has more to do with access specifiers. A programmer must first encapsulate the data and then he can take steps to hide it.

Procedural programs, for example, are not encapsulated. The procedures are grouped separately from the data. In OOP, the data is always grouped together with methods that operate upon the data.

A normal class in Java follows the encapsulation principle by default. Let’s create a basic class that deals with an employee and his tasks at the office:

public class Employeedetails {
private String employeeName;
private String employeeDept;
private int salary;
private int hoursperday;
public void work () {
}
public void train () {
}
}

As you can see, we are keeping the data that deals with the Employee together with the methods (work and train). This is encapsulation. We specified the name of the employee, his salary and hours he worked per day as private, which means only the members of the program can access this data. This helps protect the integrity of the data. Learn more about encapsulation in this advanced Java course.

Note that these are just the basic concepts. You’ve got to write your own programs and experiment with these to truly understand them. You can even write your own Java applications for Android, with the help of this course.