Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
Now Reading
12 mins read
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Java OOPs concepts are a programming paradigm based on classes, objects, and inheritance. They are used to create reusable and maintainable codes. It helps break down problems into smaller parts so developers can build, modify, and extend easy applications. This article thoroughly covers the different OOPs concepts in Java with examples.
This article deals with the different aspects of OOP in Java, such as access modifiers, message passing, and different pillars of OOPs concepts in Java. This article also touches upon OOPs concepts with examples of code and their explanations.
In Java, an access modifier is a keyword that determines the accessibility or scope of a class, variable, method, or constructor. There are four access modifiers in Java:
Private members are only accessible within the same class.
class Data {
private String name;
}
public class Main {
public static void main(String[] main){
Data d = new Data();
d.name = "zozozo";
}
}
Members with no access modifier are accessible within the same package.
package defaultPackage;
class Logger {
void message(){
System.out.println("run this message");
} }
This code does not have any executable statements. Therefore, a “main” method should be added to a separate class in order to run this code.
Members with protected access modifiers are accessible within the same package and in subclasses outside the package.
class Bird {
protected void display() {
System.out.println("I am a Bird");
}
}
class Parrot extends Bird {
public static void main(String[] args) {
Parrot parrot = new Parrot();
parrot.display();
}
}
Members with public access modifiers are accessible from anywhere in the application.
MyClass.java file:
public class MyClass {
public void display() {
System.out.println("This is an example of a public access modifier.");
}
}
Main.java file:
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
Note that to run this code, you must save it in a file named MyClass.java and another file named Main.java in the same directory.
Then, you need to compile both files together by running the following command in the terminal:
javac MyClass.java Main.java
This will generate two .class files: MyClass.class and Main.class.
Finally, run the program by executing the following command:
java Main
By using access modifiers, we can control the visibility and access of class members and encapsulate them properly to achieve data hiding and abstraction.
Message passing is a way of exchanging information between different parts of a program in Java. In message passing, objects interact by sending and receiving messages.
Message passing is a tool in Java for object-oriented programming. In this, objects in Java communicate with each other by sending and receiving messages. A message typically contains a method invocation. Other parameters are also present that are needed to perform the operation.
Method invocation means a method of an object called to perform an operation. Overall, message passing is a crucial concept in Java programming. In essence, it allows objects to communicate with each other and perform complex tasks.
Here is an example of code showing message passing in Java:
import java.util.Observable;
import java.util.Observer;
class MessageSender extends Observable {
public void sendMessage(String message) {
setChanged();
notifyObservers(message);
}
}
class MessageReceiver implements Observer {
@Override
public void update(Observable observable, Object arg) {
if (observable instanceof MessageSender) {
System.out.println("Received message: " + arg);
}
}
}
public class Main {
public static void main(String[] args) {
MessageSender sender = new MessageSender();
MessageReceiver receiver = new MessageReceiver();
sender.addObserver(receiver);
sender.sendMessage("Hello, world!");
}
}
In this example, the “MessageSender” object is an observable object. The “MessageReceiver” object is an observer object. The “MessageSender” object has a method “sendMessage()”. This sends a message to its observers. When a message is sent, the “setChanged()” method is called to mark the observable object as changed. Also, the “notifyObservers()” method is called to notify all its observers. The “MessageReceiver” object has an “update()” method that gets called when it receives a message from its observable object. The “update()” method prints the received message to the console in this example.
In Java, a class is a blueprint or a template for creating objects. It defines the attributes and behaviors of objects of a specific type. The fields of the objects show the attributes of a class. The methods of the objects show the behaviors of a class.
Here is an example of a simple class in Java:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
In this example, the “Person” class has two private fields, “name” and “age.” The “Person” class also has four public methods: “getName(),” “getAge(),” “setName(),” and “setAge().” It also has a constructor that takes in a name and an age and sets the corresponding fields.
With this class, we can create objects of the type “Person.” We can set their attributes using the “setName()” and “setAge()” methods. We can also get their attributes using the “getName()” and “getAge()” methods.
We must first add a “main” method to the “person” class with this argument:
“public static void main(String[] args) {“
Then, we can add the following code:
Person person1 = new Person("John", 25);
System.out.println("Name: " + person1.getName() + ", Age: " + person1.getAge());
Person person2 = new Person("Jane", 30);
System.out.println("Name: " + person2.getName() + ", Age: " + person2.getAge());
In Java, an object is an instance of a class. It is a basic unit of object-oriented programming. It contains both data and behavior in the form of variables and methods.
To create an object, you first need to define a class. Once you have defined a class, you can create objects of that class using the new keyword, followed by the name of the class and a set of parentheses.
For instance, if you have defined a “Person” class with properties such as “name”, “age”, and “address”, as well as methods such as “getName()” and “getAge()”. To create an object of this class, you could use the following code:
Person person = new Person("John", 25);
This creates a new “Person” object with the name "John" and the age “25”. It also assigns it to the “person” variable. You can then access the properties and methods of the object using the dot notation like this:
String name = person.getName();
int age = person.getAge();
This retrieves the name and age of the “person” object. Then it stores them in the “name” and “age” variables, respectively.
In Java, a method is a set of instructions that perform a given task. Methods allow us to organize our code and make it reusable. In Java, a method can be defined inside a class and have a return type, parameters, and access modifiers.
If we want to pass arguments to a method, we must specify the data type and name of the arguments in the method definition. When we call the method, we pass in the actual values we want to use as arguments.
Here is an example:
public class Calculator {
public int add(int x, int y) {
return x + y;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
int sum = calc.add(2, 3);
System.out.println("Sum is: " + sum);
}
}
You need to open a text editor to run this code. Then, you need to copy the code into a new file. There, you need to save the file with a “.java” extension: “Calculator.java”. Then, you need to open a terminal and navigate to the directory where you saved the file. Then, compile the code using the “javac” command: “javac Calculator.java”. Finally, run the compiled code using the “java” command: “java Calculator”. This will execute the main method of the Calculator class.
The Pillar of OOPs can also be called the features of OOPs in Java. Some key features are Abstraction, Encapsulation, Inheritance, Polymorphism, Class, and Object.
Abstraction is the process of hiding the implementation details in Java and showing only the functionality to the user. It helps to reduce the complexity of the processes and increase efficiency.
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Circle drawn");
}
}
class Rectangle extends Shape {
void draw() {
System.out.println("Rectangle drawn");
}
}
public class Main {
public static void main(String[] args) {
Shape shape = new Circle();
shape.draw();
shape = new Rectangle();
shape.draw();
}
}
Encapsulation is the mechanism of binding data members and member functions in a single unit called a class. It helps to hide the data from other classes and restrict access.
Student.java file:
public class Student {
private String name;
private int rollNo;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
}
Main.java file:
public class Main {
public static void main(String[] args) {
Student student = new Student();
student.setName("John");
student.setRollNo(1);
System.out.println("Name: " + student.getName() + ", Roll No: " + student.getRollNo());
}
}
In Java, inheritance is the process of creating a new class by inheriting properties and behavior from an existing class. It helps to reuse the code and reduce redundancy.
Here is a code explaining Inheritance:
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.bark();
}
}
Polymorphism is the ability of an object to take on many forms in Java. It is implemented using method overloading and method overriding.
class Animal {
public void makeSound() {
System.out.println("Animal is making a sound");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("Dog is barking");
}
}
class Cat extends Animal {
public void makeSound() {
System.out.println("Cat is meowing");
}
}
public class Main {
public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();
animal1.makeSound();
animal2.makeSound();
}
}
Compile-time polymorphism is a feature in Java where a class has multiple methods with the same name but different parameters or argument types. The correct method to execute is determined at compile-time based on the method signature.
Here is an example code that demonstrates compile-time polymorphism:
Calculator.java file:
public class Calculator {
public int add(int x, int y) {
return x + y;
}
public double add(double x, double y) {
return x + y;
}
}
Main.java file:
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
int sum1 = calc.add(2, 3);
System.out.println("Sum of integers: " + sum1);
double sum2 = calc.add(2.5, 3.5);
System.out.println("Sum of doubles: " + sum2);
}
}
To run this code, save it with a .java extension: “Main.java.” Then compile it using the command “javac Main.java”. Then, run the compiled code using the command “java Main.” Note that both “Calculator.java” and “Main.java” files will be saved in the same directory.
Runtime polymorphism is a process in Java to determine which method of a class is to be executed at runtime. This is based on the specified object.
Here is an example code that demonstrates runtime polymorphism:
class Animal
public void makeSound() {
System.out.println("Animal is making a sound");
}
}
class lion extends Animal {
public void makeSound() {
System.out.println("lion is roaring");
}
}
class Cat extends Animal {
public void makeSound() {
System.out.println("Cat is meowing");
}
}
public class Main {
public static void main(String[] args) {
Animal animal1 = new lion();
Animal animal2 = new Cat();
animal1.makeSound();
animal2.makeSound();
}
}
Java OOPs concepts help programmers develop robust applications. They enable developers to create complicated programs by dividing problems into smaller, more manageable components and modeling them as objects.
The Java OOPs concepts are moderately complex but can be mastered with proper guidance and training. Online learning platforms like upGrad can assist you in mastering these concepts easily.
1. What is OOP in Java?
OOP in Java stands for “Object-Oriented Programming.” The programming paradigm emphasizes using objects to represent data and behaviors.
2. What is the final method in Java?
A final method is a method that a subclass in Java cannot override.
3. What is a static block in Java?
A static block is a code block executed when a class is loaded in Java. It is typically used for static initialization.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...