top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

Java OOPs concept with code examples

In this article, you will be able to understand the basic oops concepts of Java programming language with examples. Let’s first start with what is oop!

What is OOP? OOP stands for Object-oriented programming (OOP). OOP is a computer programming model that organizes software design around data, or objects, rather than functions and logic.

Objects

A Java object is a member (instance) of a Java class. Each object has an identity, a behavior and a state. The state of an object is stored in fields (variables), while methods (functions) display the object’s behavior. Objects are created at runtime from templates, which are also known as classes. Everything in Java is associated with classes and objects, along with its attributes and methods.

For example: In real life, think about the objects present in your house. You can see a door, mirror, armchair, portrait, sofa, rug, lamp, bookcase, etc. Here, if you change your sofa, only sofa will be replaced not any other objects. So, each objects are independent.

Now, we can take armchair as an example. Here, the armchair has attributes, such as weight and color, and methods such as Recliner/Non-Recliner and Traditional/Modern, etc. Coding/Programming is nothing but sequence of instructions to perform particular operation/Function. Coding becomes more complex for big applications. If the instructions are not organized properly, then it will very tough and time consuming to pull one out without disturbing other entities. Consider, a garage with unorganized tools. Its very hard even to search and get a screw driver among all the mess. Also, it disturbs other tools position. Again it makes hard to find other tools .


Again, Consider a garage with completely organized tools as shown below. It will be very easy to get a screw or nail. It saves time. Other objects are maintained very well without any disturbance.


Let’s see about what is class!

What is class? Class is just like a blueprint for an object.


Consider car as an object. It has properties like color, wheels, body, engine, etc. Car do actions like drive, brake, etc Blueprint is not a car. With the help of blueprint, engineers can build a car (object).More objects(cars) can be produced. All cars will behave similarly. But each car can be modified as per the client wish without changing the other car properties. Hence, Object is nothing but the Actual representation of class.


Now, if you are able to understand about object and class . Then, you will definitely understand the objects oriented programming concepts very easily.

OOP’s concepts 1.Inheritance 2.Polymorphism 3.Abstraction 4.Encapsulation 5.Association 6.Aggregation 7.Composition Let’s understand first how Java OOPs Concepts are different than other programming approaches. 1. Unstructured Programming Languages Unstructured programming languages have sequential flow of control. Code is repeated through out the program. 2. Structured Programming Languages Structured Programming Languages have non-sequential flow of control. Use of functions allows for re-use of code. 3. Object Oriented Programming Languages Combines Data & Action Together. By combining data and action, we will get many advantages over structural programming language. We will see one by one. Let’s get started with Inheritance,

Inheritance Inheritance is a concept where the properties of one class can be inherited by the other class. It helps to reuse the code and establish a relationship between different classes. For example: A child inherits the properties from his/her parents. Base Class: Parent class Derived Class: Child class A class which inherits the properties is known as ‘Child Class’ whereas a class whose properties are inherited is known as ‘Parent class’. Let’s consider B as child class and A as Parent class. Try out the below code and you will get the output as shown below. class A { public int i = 10; } public class B extends A { public static void main(String[] args) { System.out.println(“class B child class inherits the value of i from parent class A”); B b = new B(); b.print(); } public void print() { System.out.println(“the value of i is” + i); } }

Output class B child class inherits the value of i from parent class A the value of i is10

Types of Inheritance 1.Single Inheritance 2.Multilevel 3.hierarchical 4.Hybrid

Single Inheritance In single inheritance, Child class inherits the properties from Parent class.

For example: Class A is your parent class and Class B is your child class. Class B inherits the properties and behavior of the parent class A.

Multilevel Inheritance In Multilevel inheritance, a class is derived from a class which is also derived from another class. A class have more than one parent class but at different levels.

For example: class B inherits from class A and class C inherits from class B. Class A is the parent class for B and class B is the parent class for C. Class C automatically inherits from both class A and Class B. This type of inheritance is called multilevel inheritance.

Hierarchical Inheritance

Just like our family Hierarchy, When a class has more than one child classes or in other words, more than one child class have the same parent class, then such kind of inheritance is known as hierarchical inheritance

For example: Class B, Class C, Class D(Child classes) inherits from Class A (Parent class).

Hybrid Inheritance Hybrid inheritance is nothing but combination of two or more types of inheritances.

Next, let’s see about polymorphism

Polymorphism If we split the word polymorphism-> poly/morph/ism, we can easily understand the meaning of it. Poly means “many/multiple”. Morph means “Forms”. So, in general, we can say like “taking different forms”. In oops, the object or variable or function can take multiple forms. In simple words, same method or interface can have multiple implementations.

There are two types of polymorphism. Types of Polymorphism 1.Run time polymorphism 2.Compile time polymorphism.

Run Time Polymorphism In Run time polymorphism, a call to an overridden method is resolved at runtime. Here, a reference variable is used to call an overridden method of a superclass at run time.

For example: Method Overriding public class RuntimePolymorphism { int a=10; int b=20; private void add() { System.out.println(“Result for class RuntimePolymorphism” + (a+b)); } public class Polymorphism { private void add() { System.out.println(“Result for class Polymorphism” + (a+b)); } } public static void main(String[] args) { RuntimePolymorphism p = new RuntimePolymorphism(); p.add(); p.new Polymorphism().add(); } }

Output Result for class RuntimePolymorphism30 Result for class Polymorphism30

Compile Time Polymorphism In compile time polymorphism, a call to an overloaded method is resolved at compile time.

For example: Method overloading (two or more methods having the same name but the arguments passed to the methods are different) public class Polymorphism { int a, b; public Polymorphism(int a, int b) { this.a = a; this.b = b; } public static void main(String[] args) { Polymorphism p = new Polymorphism(5, 10); p.add(); p.add(2, 3); p.add(1, 2, 3); } private void add() { System.out.println(“Result for First add method” + (a+b)); } public void add(int a, int b) { System.out.println(“Result for Second add method” + (a + b)); } public void add(int a, int b, int c) { System.out.println(“Result for Third add method” + (a + b + c)); } }

Output Result for First add method15 Result for Second add method5 Result for Third add method6

Abstraction In object oriented programming, we can achieve abstraction in two ways. 1.Abstract class 2.Interface

Abstract class Abstract means “Detached”. If a class is declared abstract, it cannot be instantiated. An abstract class can contain abstract as well as concrete methods. In Abstract class, User defined Method requires implementation inside abstract class. But, Abstract method inside abstract class doesn’t need any implementation. Because, Child class inherits all methods from the abstract class automatically. Additionally, we can define more methods in addition to abstract methods.

For Example: public abstract class Demo { //user defined method public int add(int a, int b){ return a +b; } //Abstract method public abstract int add(int a); }

Interface Interface is a collection of abstract methods and static constants. All methods are public and abstract. So, an interface basically is a group of related methods with empty bodies. In interface, you cannot use User defined Method. All methods will be abstract methods. For example: public interface Demo { public int add(int a, int b); public abstract int add(int a); }

Encapsulation Encapsulation refers to the wrapping up of data under a single unit. We can achieve encapsulation by declaring the variables of a class as private and creating getter and setter methods to change/view the values.

For Example: public class Encapsulation { private String studentName; public String getstudentName() { return studentName; } public void setstudentName(String name) { this.studentName = name; } public static void main(String[] args) { } } Here, the variable “studentName” cannot be accessed from other classes. But it can be accessed using getter/setter methods. Mainly, encapsulation helps to protect the data from outside.

Association, Composition and Aggregation Association is a relation between two separate classes. Composition and Aggregation are the two forms of association.



Association can be one-to-one, one-to-many, many-to-one, many-to-many. In Object-Oriented programming, an Object communicates to another object to use functionality and services provided by that object.

Aggregation is a unidirectional association. For example: A company can have employees but vice versa is not at all possible. But, both the entities can survive separately. Aggregation is a weak association.

Composition is a form of Aggregation in which two entities are highly dependent on each other. Both the entities cannot survive separately. Composition is a strong association.

For Example: import java.util.*; class employee { private String employeeName; public String getemployeeName() { return employeeName; } public void setemployeeName(String employeeName) { this.employeeName = employeeName; } @Override public String toString() { return employeeName; } } class Company { private String CompanyName; List<employee> employees; public String getCompanyName() { return CompanyName; } public void setCompanyName(String CompanyName) { this.CompanyName = CompanyName; } public List<employee> getCities() { return employees; } public void setCompany(List<employee> employees) { this.employees = employees; } } public class Association { public static void main(String[] args) { Company Company = new Company(); Company.setCompanyName(“ABC”); employee employee = new employee(); employee.setemployeeName(“Anand”); employee employee2 = new employee(); employee2.setemployeeName(“Bala”); List<employee> empList = new ArrayList<employee>(); empList.add(employee); empList.add(employee2); Company.setCompany(empList); System.out.println(Company.getCities() + “ are employees in the Company “ + Company.getCompanyName()); } }

Output [Anand, Bala] are employees in the Company ABC

Conclusion Now, you would have definitely understood the object-oriented programming concepts very well. Some of the major benefits of OOPs are as follow, 1.Improved productivity 2.Re-usability 3.Improved software maintenance 4.Easy Troubleshooting 5.Higher quality software 6.Lower cost 7.Security 8.Flexibility 9.Easily upgradable and scalable 10.Faster development Thanks for Reading. Please add your comments and let’s see in my next blog. Happy Learning!!


120 views0 comments

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page