In this article we want to learn about Java OOP Concepts, so Java is an object oriented programming language, it means that it is designed around the concepts of objects, classes and inheritance. if we understand basic principles of Object Oriented Programming, than we can write clean and maintainable code, so now let’s talk about some basics of Java OOP.
-
Classes and Objects
In Java everything is an object, and objects are created from classes. class is a blueprint or a template that defines the properties and behaviors of an object. also an object is an instance of a class. this is the basic syntax for creating a class:
1 2 3 |
public class MyClass { // class members } |
For creating an object of this class we use the following syntax:
1 |
MyClass myObject = new MyClass(); |
-
Encapsulation
Encapsulation is the concept of hiding internal details of an object and exposing only the necessary functionalities via public interface. encapsulation allows us to protect the state of an object and prevent it from being accessed or modified by external entities. for creating encapsulation we can use access modifiers such as public, private and protected.
-
Inheritance
Using inheritance one class inherits the properties and behaviors of another class. the class that is being inherited we can call it superclass or parent class, and the class that inherits from it is called subclass or child class. inheritance allows us to reuse code and create hierarchy of classes with increasing levels of abstraction.
This is the basic syntax for creating a subclass
1 2 3 |
public class MySubClass extends MySuperClass { // subclass members } |
-
Polymorphism
Using polymorphism an object can take many forms. in Java we can create polymorphism using method overriding and method overloading. method overriding occurs when a subclass provides its implementation of a method that is already defined in its superclass. method overloading occurs when a class has two or more methods with the same name but different parameters.
-
Abstraction
Abstraction is the process of identifying essential features of an object and ignoring non essential ones. it allows us to focus on what an object does instead that how it does it. in Java we can achieve abstraction by using abstract classes and interfaces. abstract class is a class that cannot be instantiated and can only be used as a superclass for its subclasses. interface is a collection of abstract methods and constants.
This is the syntax for creating an abstract class:
1 2 3 |
public abstract class MyAbstractClass { // abstract class members } |
This is the syntax for creating an interface:
1 2 3 |
public interface MyInterface { // interface members } |