LogoLogo

Java OOP Cheat Sheet — A Quick Guide to Object-Oriented Programming in Java

Prasun Das| June 23, 2022 at 4:09 PM | 13 minutes Read

Object-Oriented Programming or better known as OOPs is one of the major pillars of Java that has leveraged its power and ease of usage. If you are an aspiring Java developer, you surely need to get a flawless control over the Java OOPs concepts. To help you out, here I bring you the Java OOP Cheat Sheet. This Java OOP Cheat Sheet will act as a crash course for Java beginners and help you to gain expertise on the OOPs concepts of Java.






What is OOPS? Why do we need it?

Object-oriented programming (OOP) is a computer programming model in which software design is organised around data, or objects, rather than functions and logic. An object is a data field that has distinct attributes and behaviour.

In layman's terms, a class can be thought of as a blueprint or template from which objects can be created. As a result, Objects are considered instances of a class and are sometimes referred to as "instances." The term "characteristics" refers to the "what" of the Object, while "behaviour" refers to the "how" of the Object.





What is the structure of object-oriented programming?

The structure, or building blocks, of object-oriented programming include the following:




  1. Classes are custom data types that serve as the foundation for individual objects, attributes, and methods.
  2. Objects are instances of a class that are created with specific data. Objects can be real-world objects or abstract entities.
  3. Methods are functions defined within a class that describe an object's behaviour. Every method in a class definition begins with a reference to an instance object. In addition, the subroutines contained within an object are referred to as instance methods. Methods are used by programmers to ensure reusability or to keep functionality contained within a single object at a time.
  4. Attributes are defined in the class template and represent an object's state. Data will be stored in the attributes field of objects. Class attributes are owned by the class.



What are the criteria for a programming language to be completely object oriented?

Pure Object Oriented Language (POOL) or Complete Object Oriented Language (COOL) is a Fully Object Oriented Language that supports or has features that treat everything inside the programme as objects. It does not accept primitive data types (like int, char, float, bool, etc.). There are seven requirements for a programming language to be pure Object Oriented. They are as follows:

1.Encapsulation/Data Hiding

2.Inheritance

3.Polymorphism

4.Abstraction

5.All predefined types are objects

6.All user defined types are objects

7.All operations performed on objects must be only through methods exposed at the objects.



Why Java is not considered to be completely Object Oriented?

Java language is not a Pure Object Oriented Language as it contain these properties:


 1. Primitive Data Type ex. int, long, bool, float, char, etc as Objects: Smalltalk is a “pure” object-oriented programming language unlike Java and C++ as there is no difference between values which are objects and values which are primitive types. In Smalltalk, primitive values such as integers, booleans and characters are also objects.

In Java, we have predefined types as non-objects (primitive types).




int a = 5;
System.out.print(a);

2.The static keyword: When we declare a class as static then it can be used without the use of an object in Java. If we are using a static function or static variable then we can’t call that function or variable by using dot(.) or class object defying object oriented features.

3. Wrapper Class: Wrapper class provides the mechanism to convert primitive into object and object into primitive. In Java, you can use Integer, Float etc. instead of int, float etc. We can communicate with objects without calling their methods. ex. using arithmetic operators.




String s1 = "ABC" + "A" ;

Even using Wrapper classes does not make Java a pure OOP language, as internally it will use the operations like Unboxing and Autoboxing. So if you create instead of int Integer and do any mathematical operation on it, under the hoods Java is going to use primitive type int only.





publicclassBoxingExample
{
publicstaticvoidmain(String[] args)
{
        Integer i = new Integer(10);
        Integer j = new Integer(20);
        Integer k = new Integer(i.intValue() + j.intValue());
            System.out.println("Output: "+ k);
}
}

In the above code, there are 2 problems where Java fails to work as pure OOP:


While creating Integer class you are using primitive type “int” i.e. numbers 10, 20.

While doing addition Java is using primitive type “int”.





Constructor

A function Object() { [native code] } is a special method in Java that is used to initialise objects. When a class object is created, the function Object() { [native code] } is called. It can be used to initialise the values of object attributes.

A function Object() { [native code] } in Java is a block of code that is similar to a method. When a new instance of the class is created, it is called. Memory for the object is allocated in the memory when the function Object() { [native code] } is called. It is a type of method that is used to initialise an object. At least one function Object() { [native code] } is called every time an object is created with the new() keyword.



Note: 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.

So constructors are used to assigning values to the class variables at the time of object creation, either explicitly done by the programmer or by Java itself (default constructor).


When is a Constructor called?

Each time an object is created using a new() keyword, at least one constructor (it could be the default constructor) is invoked to assign initial values to the data members of the same class.


The rules for writing constructors are as follows:





  1. Constructor(s) of a class must have the same name as the class name in which it resides.
  2.  A constructor in Java can not be abstract, final, static, or Synchronised.
  3.  Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.


Types of Constructors in Java





  1. No-argument constructor(Default): Created by the compiler itself if not by the prog
  2. Parameterized Constructor: If we want to initialise fields of the class with our own values, then use a parameterized constructor.


Does constructor return any value?


There are no “return value” statements in the constructor, but the constructor returns the current class instance. We can write ‘return’ inside a constructor.


How Constructors are Different From Methods in Java?

Constructors must have the same name as the class within which it is defined while it is not necessary for the method in Java.

Constructors do not return any type while method(s) have the return type or void if it does not return any value.

Constructors are called only once at the time of Object creation while method(s) can be called any number of times.


Note: Now the most important topic that comes into play is the strong incorporation of OOPS with constructors known as constructor overloading. Just like methods, we can overload constructors for creating objects in different ways. Compiler differentiates constructors on the basis of numbers of parameters, types of the parameters, and order of the parameters.






Classes and Objects

Class in Java determines how an object will behave and what the object will contain. A class consists of data members (attributes, field, variables) which gives its objects their properties and methods which define the behaviour of the objects.


Syntax of Class in Java




class <class_name>{ 
field; 
    method; 
  }



An object consists of :


State: It is represented by attributes of an object. It also reflects the properties of an object.

Behaviour: It is represented by methods of an object. It also reflects the response of an object with other objects.

Identity: It gives a unique name to an object and enables one object to interact with other objects.


Syntax of Object Creation in Java




class_name object_name = new class_name();


 The Java new keyword is used to create an instance of the class. In other words, it instantiates a class by allocating memory for a new object and returning a reference to that memory. We can also use the new keyword to create the array object

Ways to initialise object

There are 3 ways to initialise objects in Java.




  1. By reference variable
  2. By method
  3. By constructor


Example of an object: car







MODIFIERS IN JAVA

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it.

There are four types of Java access modifiers:




  1. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
  2. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.
  3. Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.
  4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.


There are many non-access modifiers, such as static, abstract, synchronised, native, volatile, transient, etc.





Non Access Modifiers in Java



ENCAPSULATION (Data Hiding)



Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class.



To achieve encapsulation in Java −





  1.  Declare the variables of a class as private.
  2.  Provide public setter and getter methods to modify and view the variables values.



Therefore, data can be only accessed by these specific methods (getters and setters) and hence the objects properties are hidden from the outside world.


Benefits of Encapsulation




  1.  The fields of a class can be made read-only or write-only.
  2.  A class can have total control over what is stored in its fields.



INHERITANCE

Inheritance is one of the most important concepts of Object-Oriented Programming. Inheritance is the capability of one class to inherit capabilities or properties from another class in Java. For instance, we are humans.

The principle behind this kind of division is that each subclass (child-class) shares common characteristics with the class from which it is derived.

·    Automobiles and Pulled Vehicles are subclasses of Vehicles.

·    Vehicles are the base class or superclass of Automobiles and pulled Vehicles.

·    Car and Bus are sub-classes or derived classes of Automobiles.

·    Automobiles are the base class or superclass of Car and Bus.



Important terminologies:

1. Super Class: The class whose features and functionalities are being inherited or used is known as the superclass or a base class or a parent class.

2. Sub Class: The class that inherits the properties and features from another class is known as a subclass or a derived class or extended class or child class. The subclass can add its own features and functions in addition to the fields and methods of its superclass or the parent class.

3. The extends keyword: The keyword extends is used by child class while inheriting the parent class.

4. The super keyword: The super keyword is similar to this keyword. The following are some cases where we use super keyword :

·    There are some situations where the members of the superclass and the subclass have the same names, then the super keyword is used to differentiate the members of the superclass from the members of the subclass.

·    To invoke the superclass constructor from the subclass.


Syntax of using Inheritance in Java:

We already know that to inherit a class, we use the extends keyword. The syntax of using inheritance in Java is:




classBaseClass
{
//methods and fields
}
classDerivedBaseClassextendsBaseClass
{
//methods and fields
}





Types of inheritance in java



1.Single Inheritance


Derived class(child class) inherit properties and behavior from single super class(parent class).

Look the following example code;

In this example Super class is Animal and Sub class is Dog. We create a class called Animal and create a method ‘eat()’.Think you want to display special features of a dog. So if you add those changes to Animal class it should affect whole code.


So in that case we can use inheritance.

We create a Dog class which extends from Animal class. Dog class contain all the properties of Animal class. So we can call features of both class

Extends keyword use to indicates that child class is inherited by super class.




Output
They Eat….
Dog is Barking…



2.Multilevel Inheritance

class having more than one Super class at different levels such type inheritance are known as Multilevel Inheritance.

Here, Child1 class inherits the properties of parent classChild11 class inherits the properties of Child1 class. For Child11 class, Child1 class is a Super class. Child11 class implicitly inherits features of both Child1 class and Parent class.

example code:

BabyDog d=new BabyDog();

BabyDog class can get all the properties in both Dog class and Animal class.




Output
They Eat….
Dog is Barking…
Baby Dog is Crying….



3.Hierarchical Inheritance

If super class(parent class) have more than one sub classes(children class) such kind of inheritance are known as Hierarchical Inheritance.

Both Child1 class and Child2 class are inheriting from Parent class.

Dog class and Cat class are Sub classes which are inheriting from Animal class(parent class).


4.Hybrid Inheritance

Combination of Multilevel inheritance and Multiple inheritance.

I explained about Multilevel inheritance .






What are Multilevel inheritance?

Multilevel inheritance are not support to java because it makes ambiguity.


As an example think there are 3 classes A, B and C. class C inherits from class A and B. if there is a same method in both A and B, when you call that method from child class(class C) there will be an ambiguity to call the method of class A or class B.




Why java doesn't support multiple and hybrid inheritance?

The reason behind this is to prevent ambiguity. Consider a case where class B extends class A and Class C and both class A and C have the same method display(). Now java compiler cannot decide which display method it should inherit. To prevent such a situation, multiple inheritance is not allowed in java.






Hybrid inheritance is the combination of every type of inheritance that exist. As java doesn't support multiple inheritance, hybrid inheritance also can't be implemented. Similarly, as multiple inheritance is implemented through interfaces, hybrid inheritance can be implemented with the help of interface.


POLYMORPHISM

Polymorphism is the ability of a variable, function or an object to take multiple forms. It allows you to define one interface or method and have multiple implementations.





There are two types of polymorphism in Java.




  1. Compile Time Polymorphism
  2. Runtime Polymorphism





Compile Time Polymorphism

Also called static binding, as the type of the object is determined at the compile time by the compiler itself.

Example: Method Overloading: If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.

There are two ways to overload the method in java




  1. By changing number of arguments
  2. By changing the data type





classCalculator {
staticintadd(int a, int b){
return a+b;
}
staticdoubleadd(double a, double b){
return a+b;
}
publicstaticvoidmain(String args[]){
System.out.println(Calculator.add(123,17));
System.out.println(Calculator.add(18.3,1.9));
}
}





Runtime Polymorphism

Also called dynamic binding as the overridden method is resolved at runtime rather than compile-time. In this, a reference variable is used to call an overridden method of a superclass at run time.

Example: Method Overriding:If subclass (child class) has the same method as declared in the parent class, it is known as method overriding.

In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding.





publicclassMobile{
voidsms(){
System.out.println("Mobile class");
}
} //Extending the Mobile classpublic class OnePlus extends Mobile{ //Overriding sms() of Mobile classvoid sms(){
System.out.println(" OnePlus class");
}
publicstaticvoidmain(String[] args)
{
OnePlus smsObj= new OnePlus();
smsObj.sms();
}
}


ABSTRACTION

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message. You don't know the internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.





Ways to achieve Abstraction

There are two ways to achieve abstraction in java




  1. Abstract class (0 to 100%)
  2. Interface (100%)


Abstract Class

Abstract Class is a class which is declared with an abstract keyword and cannot be instantiated. Few pointers to create an abstract class:

·    It can contain abstract and non-abstract methods.

·    It can contain constructors and static methods as well.

·    It can contain final methods which force the subclass not to change the body of the method.




publicabstractclassMyAbstractClass
 {
publicabstractvoidabstractMethod();
publicvoiddisplay(){ System.out.println("Concrete method"); }
}






Interface





An interface in java is a blueprint of a class that contains static constants and abstract methods. It represents the IS-A relation. You need to implement an interface to use its methods or constants.




//Creating an Interfacepublic interface Bike { public void start(); }//Creating classes to implement Bike interfaceclass Honda implements Bike{ public void start() { System.out.println("Honda Bike"); } }classApacheimplementsBike{
publicvoidstart(){ System.out.println("Apache Bike"); }
}
classRider{
publicstaticvoidmain(String args[]){
Bike b1=new Honda();
b1.start();
Bike b2=new Apache();
b2.start();
}
}





What are the benefits of OOP?

·    Modularity. Encapsulation enables objects to be self-contained, making troubleshooting and collaborative development easier.

·    Reusability. Code can be reused through inheritance, meaning a team does not have to write the same code multiple times.

·    Productivity. Programmers can construct new programs quicker through the use of multiple libraries and reusable code.

·    Easily upgradable and scalable. Programmers can implement system functionalities independently.

·    Interface descriptions. Descriptions of external systems are simple, due to message passing techniques that are used for objects communication.

·    Security. Using encapsulation and abstraction, complex code is hidden, software maintenance is easier and internet protocols are protected.

·    Flexibility. Polymorphism enables a single function to adapt to the class it is placed in. Different objects can also pass through the same interface.





This blog gives you a rough pathway of core questions ans topics to follow. Ofcourse, you can and should explore more on your journey. There will be new blogs coming on Java interview preparation soon, so stay tuned. Also, if you have any particular topic that you want covered, please write to us. If you wanna connect with me, here is my linkedin profile — Sneha Biswas. If you have any questions, feel free to contact me.

#object oriented programing#java#fundamentals to learn
View Count:1.9k
0

Comments

Similar Articles

Busting myths about web3

WHAT IS WEB3?Web3 is the catch-all term for the vision of an upgraded version of the internet aimed at giving power back to the users. It is truly the......

Cover image

Operating System INTERVIEW QUESTIONS

Operating Systems is one of the core subjects for a computer science student. As such a lot of important questions are asked on this subject in interv......

Cover image

Cloud Computing Cheatsheet

Getting started with cloud computing ?The words "cloud" and "web" will be interchangeable. What kind of business operates today without the internet? ...

Cover image

Software Engineering — SOFTWARE MAINTENANCE [Part-4]

SOFTWARE MAINTENANCE:Software Maintenance can be defined as the process of modifying a software product after its delivery. The main purpose of softwa...

Cover image

Software Engineering — Software Process Activities [Part - 3]

A quick summary upto what we did this far&nbsp; from this series:Software EngineeringSoftware engineering is a discipline of engineering concerned wit...

Cover image

Understanding Time Complexity with Interview Examples

Introduction:Understanding time complexity of a function is imperative for every programmer to execute a program in the most efficient manner. Time co...

Cover image

Software Engineering — Software Development lifecycle and software process(Part 2)

&nbsp;Software MethodologyA software methodology (which is also known as software process) is a set of related development Phases that leads to the pr...

Cover image

Software Engineering [Part 1] - Introduction

Software Engineering is a subject that requires when you are a software developer as well as when you are in your college preparing for a semester or ...

Cover image

SQL Interview Questions

Are you getting ready for your SQL developer job interview?You've come to the correct place.This tutorial will assist you in brushing up on your SQL s...

Cover image

SQL CHEATSHEET

Introduction: What is SQL?To understand SQL, we must first understand databases and database management systems (DBMS).Data is essentially a collectio...

Cover image

Computer Networking Cheatsheet (Last Minute Notes)

&nbsp;Networking: Importance in real life!Using a computer for work, as well as for personal use, ha...

Cover image

Database Management System Last Minute Notes [Part - 2]

ER-DiagramWhat are ER Models ?An Entity Relationship Diagram (ERD) is a visual representation of dif...

Cover image

Database Management System Last Minute Notes [Part - 1]

What is actually DBMS?A Database Management System (DBMS) is system software used to manage the orga...

Cover image

C Cheatsheet

C CHEATSHEETINTRODUCTION:C programming language was developed by Dennis Ritchie of Bell Labs in 1972...

Cover image

C Interview Questions — 2022

C is a general purpose high-level language most popular amongst coders, it is the most compatible, e...

Cover image

C++ STL Cheat Sheet

C++ programming language has templates which basically allows functions and classes to work with gen...

Cover image

C++ CHEAT SHEET

C++ was conceived in the late 1970s to overcome the limitations of C. It&nbsp; is an extension of th...

Cover image

Python [Advanced] Interview Questions — 2022

Interview Questions are a great source to test your knowledge about any specific field. But remember...

Cover image

Basic Python [Core] Interview Questions for Freshers and Short Sample Answers — 2022

The most popular high-level, multipurpose programming language right now is Python.Python supports p...

Cover image

Python Cheat Sheet - Learn the basics of Python

IntroductionPython is a high-level programming language with dynamic binding and high-level inherent...

Cover image

Basic Java Interview Questions for Freshers and Short Sample Answers — 2022

Interview Questions are a great source to test your knowledge about any specific field. But remember...

Cover image

Learn Java: Basics to Advanced Concepts [Java Cheatsheet]

Java is a high-level programming language known for its robustness, object-oriented nature, enhanced...

Cover image