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
Now Reading
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
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 is a widely-used programming language. It is lauded for its ability to create flexible and scalable applications. Central to this language is the concept of "Java Classes and Objects". These foundational principles, crucial to mastering Java, facilitate better code organization and reusability.
The Java programming language is built on the principles of Object-Oriented Programming (OOP). This model organizes software design around data, or objects, rather than functions and logic. An object can be defined as a data field with unique attributes and behavior. Java classes, on the other hand, are templates used to create objects.
In Java, the foundational building blocks are Classes and Objects. A class, much like an architectural blueprint, sets a structure that can be followed. It lays out a framework, dictating the behavior and state that objects created from the class will have.
Whereas “Objects” are instances of a class. Each object is an entity in itself, possessing its own state and behavior, as defined by the class. Understanding this interrelation between classes and objects is vital to mastering Java.
// Define a 'Car' class
class Car {
// Attributes of the class
String brand;
String model;
int year;
double price;
// Constructor to initialize the object
Car(String brand, String model, int year, double price) {
this.brand = brand;
this.model = model;
this.year = year;
this.price = price;
}
// Method to display car details
void displayDetails() {
System.out.println("Brand: " + this.brand);
System.out.println("Model: " + this.model);
System.out.println("Year: " + this.year);
System.out.println("Price: $" + this.price);
}
}
// Main class
public class Main {
public static void main(String[] args) {
// Create an object of the 'Car' class
Car car1 = new Car("Toyota", "Camry", 2020, 24000.00);
// Call the method to display details
car1.displayDetails();
}
}
In this example, we've defined a ‘Car’ class with attributes for brand, model, year, and price. We've also created a constructor to initialize these attributes when we create a ‘Car’ object, and a method ‘displayDetails()’ to print out the details of the car.
In the ‘main()’ method, we create an object ‘car1’ of the ‘Car’ class, passing values to the constructor. We then call the ‘displayDetails()’ method on ‘car1’ to print out its details.
When you run this program, it should output:
In Java, a class is a blueprint from which individual objects can be constructed. It comprises a Class Name, Body, and Types of Classes. Let's examine each of these in detail.
In Java, a class name is a label given to a class. For instance, consider ‘public class Car’. Here, 'Car' is the class name.
The body of the class, enclosed within curly braces {}, contains all the variables and methods. For example:
public class Car {
// variables
String color;
String model;
// methods
void start() {
// some code
}
void stop() {
// some code
}
}
In Java, there are many sorts of classes:
abstract class Vehicle {
abstract void run();
}
Interfaces in Java play a key role in establishing a contract for what a class can do, without saying anything about how the class will do it. They ensure that a class adheres to a certain contract, without caring about the class's inheritance hierarchy.
interface Playable {
void playMusic();
}
In this example, ‘Playable’ is an interface that declares a method named ‘playMusic()’. Any class implementing ‘Playable’ will have to provide an implementation for the ‘playMusic()’ method.
Creating a class in Java is akin to crafting a blueprint for a type of object. It involves defining the class name and the class body which includes variables (state) and methods (behavior).
Here's a simple example to show creating a class:
public class Dog {
// Class variables or properties
String name;
String breed;
int age;
// Class methods or behaviors
public void bark() {
System.out.println("Woof!");
}
public void sleep() {
System.out.println("Zzz...");
}
public void eat() {
System.out.println("Yum!");
}
public static void main(String[] args) {
// Create an object of the 'Dog' class
Dog myDog = new Dog();
// Set dog attributes
myDog.name = "Buddy";
myDog.breed = "Golden Retriever";
myDog.age = 3;
// Call methods to make the dog bark, sleep, and eat
myDog.bark();
myDog.sleep();
myDog.eat();
}
}
In this example, we've created a ‘Dog’ class, defined by the keyword ‘class’. This ‘Dog’ class has three properties (‘name’, ‘breed’, and ‘age’) and three behaviors (‘bark()’, ‘sleep()’, and ‘eat()’).
These properties and behaviors are the characteristics of any ‘Dog’ object created from this class.
Objects in Java are fundamental components that represent real-world entities. Each object has an identity, state, and behavior. Let's examine these attributes.
An object's identity is akin to a person's DNA; it's unique and distinguishes it from other objects, even if their states and behaviors are identical. In Java, this identity is provided by the JVM in the form of a unique memory location, not usually manipulated directly in your code.
The state of an object is represented by its attributes or fields, essentially the data stored within the object. For instance, if we have a ‘Dog’ class, the state could include attributes like ‘breed’, ‘size’, ‘age’, and ‘color’.
The behavior of an object is depicted by its methods. These are actions the object can perform, often operating on the object's state. For example, a ‘Dog’ object could have behaviors such as ‘bark()’, ‘eat()’, and ‘sleep()’.
Here's a simple example to illustrate a Java object:
public class Dog {
// State Of Dog
String breed;
String size;
int age;
String color;
// Behavior
void bark() {
// Some code for barking behavior
}
void eat() {
// Some code for eating behavior
}
void sleep() {
// Some code for sleeping behavior
}
public static void main(String[] args) {
// Create a new Dog object
Dog myDog = new Dog();
// Initialize the dog's attributes
myDog.breed = "Labrador";
myDog.size = "Large";
myDog.age = 3;
myDog.color = "Golden";
// Perform some actions on the dog
myDog.bark();
myDog.eat();
myDog.sleep();
}
}
In this code, ‘myDog’ is an object of the class ‘Dog’. It has its own state (breed, size, age, color) and behavior (bark, eat, sleep).
Creating an object in Java is a two-step process. Let's use our previously discussed Dog class to create a Dog object:
Dog myDog ;
In this line of code, we declare a ‘Dog’ object called ‘myDog’.
myDog = new Dog();
Now, ‘myDog’ is an object of the ‘Dog’ class. You can now use the dot syntax of class in Java to access fields and methods:
myDog.breed = "Labrador" ;
myDog.size = "Large" ;
myDog.age =5
myDog.Color = "Yellow" ;
Here, we're setting the state of the ‘myDog’ object. Remember, each object has its own state independent of the other objects.
Declaring objects in Java is a pivotal first step in the object lifecycle. This declaration doesn't create a new object, but instead prepares the way for an object to exist in memory.
Here's what it looks like to declare an object of a ‘Dog’ class:
Dog myDog ;
In this simple line of code, we're stating that ‘myDog’ is going to be an object of type ‘Dog’. However, it's worth noting that ‘myDog’ isn't an actual ‘Dog’ object yet—it's just a reference that can point to a ‘Dog’ object. In memory, it doesn't yet have the characteristics or behaviors defined in the ‘Dog’ class.
To actually create a ‘Dog’ object in memory, we need to instantiate the ‘Dog’ class using the ‘new’ keyword:
myDog = new Dog();
Now, ‘myDog’ is an instance of ‘Dog’, meaning it has all the characteristics and behaviors defined in the ‘Dog’ class.
Remember, object declaration and instantiation are separate steps in Java, although they can be done in the same line for convenience:
Dog myDog = new Dog();
Initializing objects in Java refers to the process of assigning initial values to the object's fields (or attributes). This is typically done at the time of object creation (though it can be done later) and ensures your object starts in a valid state.
You can initialize an object in Java in many ways:
You can directly assign values to the object's fields:
Dog myDog = new Dog( ) ;
myDog.breed = "Labrador";
myDog.size = "Large" ;
myDog. Age = 5;
myDog.color = "Yellow";
You can use a method or function to initialize an object's fields:
public class Dog {
String breed;
String size;
int age;
String color;
// Initialization method
void initialize(String breed, String size, int age, String color) {
this.breed = breed;
this.size = size;
this.age = age;
this.color = color;
}
public static void main(String[] args) {
// Creating and initializing the object
Dog myDog = new Dog();
myDog.initialize("Labrador", "Large", 5, "Yellow");
// Print the dog's attributes
System.out.println("Breed: " + myDog.breed);
System.out.println("Size: " + myDog.size);
System.out.println("Age: " + myDog.age);
System.out.println("Color: " + myDog.color);
}
}
Here, we've defined an ‘initialize’ method in the ‘Dog’ class. This method takes in parameters and assigns them to the object's fields. Note the use of ‘this’, which is a reference to the current object.
There are numerous methods for creating objects in Java.
This is the most common method for creating objects. It involves declaring a variable of a class type, and then using the ‘new’ keyword to create the object:
Dog myDog = new Dog();
This method can be used when the name of the class is available at runtime. It returns the instance of ‘Class’ class which can be used to create objects:
class Dog {
// Add necessary methods and attributes to the Dog class
void bark() {
System.out.println("Dog is barking");
}
void eat() {
System.out.println("Dog is eating");
}
void sleep() {
System.out.println("Dog is sleeping");
}
}
public class Main {
public static void main(String[] args) {
try {
Class<?> cls = Dog.class;
Dog myDog = (Dog) cls.getDeclaredConstructor().newInstance();
// Perform actions on myDog
myDog.bark();
myDog.eat();
myDog.sleep();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The method creates and returns a copy of the object:
Dog myDog1 = new Dog();
Dog myDog2 ;
try {
myDog2 = (Dog) myDog1. clone() ;
} catch (CloneNotSupportedException e){
e. printStackTrace( ) ;
}
Object deserialization is the process of converting the serialized bytes back into a copy of the original object:
// Assumes myDog has been serialized to 'dog. ser' file
try {
FileInputStream file = new FileInputStream( "dog . set");
ObjectlnputStream in = new ObjectlnputStream(fi1e) ;
Dog myDog = (Dog) in. readObject() ;
in. close();
file. close( ) ;
} catch (IOException I ClassNotFoundException e) {
e. printStackTrace( ) ;
}
The ‘newInstance()’ method of ‘Constructor’ class is used to create and return a new instance of the constructor's declaring class, completed as if by a call to the constructor:
try {
Constructor<Dog> constructor = Dog.class.getConstructor();
Dog myDog= constructor.newlnstance();
} catch (NoSuchMethodException I InvocationTargetException |
InstantiationException I IllegalAccessException e) {
e.printStackTrace();
}
Each of these methods suits different scenarios, and their usage depends on the requirements of your program.
In Java, it's a common practice to create multiple objects of the same type, especially when you're dealing with collections of similar items.
For example, if we're dealing with a group of dogs, we might create multiple ‘Dog’ objects like this:
Dog dog1= new Dog();
Dog dog2= new Dog();
Dog dog3= new Dog();
Each ‘Dog’ object can have its own unique properties:
dog 1.breed = "Labrador";
dog1.age = 5;
dog1. Color = "Yellow";
dog2. Breed = "Beagle";
Dog2.age = 3;
dog2. color= "Tri-color";
dog3. breed = "Dalmatian";
dog3. Age = 4;
dog3.color = "Spotted White and Black" ;
In this way, we're able to maintain multiple unique ‘Dog’ objects, each with its own state and behaviors.
In the realm of object-oriented programming, classes, and objects are two sides of the same coin. However, they play distinct roles in your code.
Class | Object | |
Definition | A class is a blueprint or template for an object. | An object is an instance of a class. |
Logic | A class is a logical entity. | An object is a physical entity. |
Existence | A class doesn't exist in memory when the program runs. | An object exists in memory when the program runs. |
Fields | Fields within a class are the variables it contains. | Fields within an object store its state. |
Modification | Changes to a class affect all its objects. | Changes to an object affect that object only. |
Creation | Defined once in code. | Can be created many times based on the class. |
As we've explored Java Classes and Objects, understanding classes and objects is key to mastering Java. Classes, as blueprints, provide the foundation for objects. Objects, as instances of classes, breathe life into your programs.
Encapsulation in Java is like putting data and related actions in a box. Classes are like these boxes that hold the data and actions together for objects. It helps keep things organized, secure, and prevents unwanted access to the internal data of objects.
Yes, a class in Java can have different ways to create objects, which are called constructors. Each constructor provides a different way to initialize or set up the object, depending on the parameters or requirements you have.
Inheritance in Java allows a class to inherit the characteristics of another class. By extending a class, you can create a new class (child class) that inherits the properties and behaviors of an existing class (parent class). This helps with code reuse and creating a hierarchy of classes.
When you use the "static" keyword with class members, like variables or methods, it means they belong to the class itself, rather than individual objects. It's like a shared resource that all objects of the class can access and use. You don't need to create an object to access static members, and they are handy for utility functions or data shared across objects of the class.
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...