⬅ Previous Topic
Java Class ConstructorNext Topic ⮕
Java Access Modifiers⬅ Previous Topic
Java Class ConstructorNext Topic ⮕
Java Access ModifiersIn Java, everything starts with objects. Whether you're building a banking system, a video game, or an e-commerce platform, objects are the building blocks. If classes are blueprints, objects are the actual houses built from those blueprints.
An object is a runtime instance of a class. It is an entity that has:
To create an object, we use the new
keyword followed by the class constructor. Here's a simple example:
class Dog {
String name;
int age;
void bark() {
System.out.println(name + " says: Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog(); // Creating an object
myDog.name = "Buddy";
myDog.age = 3;
myDog.bark(); // Calling a method on the object
}
}
Buddy says: Woof!
In the above program:
Dog
is the class – the blueprint.myDog
is the object – the actual dog instance.myDog.bark()
.You can create as many objects as you want from a single class. Each will have its own copy of fields and methods.
public class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.name = "Max";
dog1.age = 4;
Dog dog2 = new Dog();
dog2.name = "Bella";
dog2.age = 2;
dog1.bark();
dog2.bark();
}
}
Max says: Woof!
Bella says: Woof!
When you create an object using new
, Java allocates memory on the heap. The variable (myDog
) stores a reference (address) to that memory location.
Instead of setting each field manually, we can initialize values using a constructor.
class Dog {
String name;
int age;
Dog(String n, int a) {
name = n;
age = a;
}
void bark() {
System.out.println(name + " barks at age " + age);
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Rocky", 5);
dog.bark();
}
}
Rocky barks at age 5
Methods that work on object-specific data (like bark()
) are instance methods. You call them through objects. We'll cover static
(class-level) methods in another tutorial.
Think of a class like a "Car" manual, and an object like an actual car you can drive. Multiple people can build cars from the same manual, but each car has its own color, speed, and mileage.
Java is an Object-Oriented Programming language. Understanding objects is foundational for:
To recap:
new
keyword is used to create object instances.new
keyword in object creation?class Dog {
String name;
void bark() {
System.out.println(name + " says: Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.name = "Buddy";
myDog.bark();
}
}
⬅ Previous Topic
Java Class ConstructorNext Topic ⮕
Java Access ModifiersYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.