Object-Oriented Programming Basics
Object-Oriented Programming Basics
Learn the fundamentals of Object-Oriented Programming in Java.
1. What is a Class?
A class is a blueprint or template for creating objects. It defines the properties (attributes) and behaviors (methods) that the objects of the class will have.
// Class definition
class Student {
// Fields (attributes)
String name;
int age;
// Method
void study() {
System.out.println(name + " is studying.");
}
}
2. What is an Object?
An object is an instance of a class. It's a concrete entity based on a class and contains actual values.
// Creating objects of Student class
Student student1 = new Student();
student1.name = "Alice";
student1.age = 20;
student1.study(); // Output: Alice is studying.
Student student2 = new Student();
student2.name = "Bob";
student2.age = 22;
3. What is State of an Object?
The state of an object is represented by its attributes (instance variables) and their current values.
// State of student1 object
System.out.println("Name: " + student1.name); // State: name = "Alice"
System.out.println("Age: " + student1.age); // State: age = 20
4. What is Behavior of an Object?
Behavior is represented by methods of the class and shows what an object can do.
class Dog {
String name;
// Behaviors
void bark() {
System.out.println(name + " says: Woof!");
}
void eat() {
System.out.println(name + " is eating.");
}
}
Dog myDog = new Dog();
myDog.name = "Buddy";
myDog.bark(); // Behavior: Makes the dog bark
myDog.eat(); // Behavior: Makes the dog eat
5. What is the Super Class of Every Class in Java?
In Java, Object class (java.lang.Object) is the superclass of all other classes either directly or indirectly.
// Every class implicitly extends Object
class MyClass { // Equivalent to: class MyClass extends Object
// class body
}
// Common Object class methods
Object obj = new Object();
obj.toString(); // Returns string representation
obj.hashCode(); // Returns hash code
obj.equals(obj2); // Compares objects for equality
6. Inheritance with Examples
Inheritance allows a class to inherit fields and methods from another class. The class being inherited from is called the superclass, and the class that inherits is called the subclass.
// Base class (Superclass)
class Animal {
void eat() {
System.out.println("Animal is eating");
}
void sleep() {
System.out.println("Animal is sleeping");
}
}
// Derived class (Subclass)
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
// Method overriding
@Override
void eat() {
System.out.println("Dog is eating dog food");
}
}
// Using the classes
Dog myDog = new Dog();
myDog.eat(); // Calls overridden method in Dog
myDog.sleep(); // Inherited from Animal
myDog.bark(); // Specific to Dog
7. What is Method Overloading?
Method overloading allows a class to have multiple methods with the same name but different parameters.
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Overloaded method to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Overloaded method to add two doubles
double add(double a, double b) {
return a + b;
}
}
Calculator calc = new Calculator();
System.out.println(calc.add(5, 3)); // Calls first method
System.out.println(calc.add(5, 3, 2)); // Calls second method
System.out.println(calc.add(2.5, 3.7)); // Calls third method
8. What is Method Overriding?
Method overriding occurs when a subclass provides a specific implementation of a method that is already provided by its superclass.
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Cat says: Meow!");
}
}
Animal myAnimal = new Animal();
myAnimal.makeSound(); // Output: Animal makes a sound
Cat myCat = new Cat();
myCat.makeSound(); // Output: Cat says: Meow!
9. Can Super Class Reference Variable Hold an Object of Sub Class?
Yes, a superclass reference variable can refer to a subclass object. This is known as upcasting.
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
@Override
void eat() {
System.out.println("Dog is eating");
}
void bark() {
System.out.println("Dog is barking");
}
}
// Superclass reference to subclass object
Animal myPet = new Dog(); // Valid: Upcasting
myPet.eat(); // Calls Dog's eat() method
// myPet.bark(); // Error: Cannot call bark() using Animal reference
10. Is Multiple Inheritance Allowed in Java?
Java doesn't support multiple inheritance of classes (a class can't extend more than one class) to avoid the "diamond problem". However, it supports multiple inheritance through interfaces.
// Multiple inheritance using interfaces
interface Swimmer {
void swim();
}
interface Flyer {
void fly();
}
// Class implementing multiple interfaces
class Duck implements Swimmer, Flyer {
@Override
public void swim() {
System.out.println("Duck is swimming");
}
@Override
public void fly() {
System.out.println("Duck is flying");
}
}
Duck duck = new Duck();
duck.swim();
duck.fly();
11. What is a Constructor?
A constructor is a special method that's called when an object is instantiated. It has the same name as the class and has no return type.
class Book {
String title;
String author;
// Parameterized constructor
public Book(String title, String author) {
this.title = title;
this.author = author;
}
// Method
void displayInfo() {
System.out.println("Title: " + title + ", Author: " + author);
}
}
// Creating object using constructor
Book myBook = new Book("Java Programming", "John Doe");
myBook.displayInfo(); // Output: Title: Java Programming, Author: John Doe
12. What is a Default Constructor?
If a class doesn't have any constructor, the Java compiler automatically creates a default constructor (no-argument constructor).
class Person {
String name;
int age;
// No constructor defined
// Java provides a default constructor: Person() {}
}
Person person = new Person(); // Uses default constructor
person.name = "Alice";
person.age = 25;
13. Will This Code Compile?
If you define any constructor in a class, Java won't provide the default constructor anymore. You need to explicitly define it if needed.
class Student {
String name;
// Parameterized constructor
Student(String name) {
this.name = name;
}
// Uncomment to fix compilation error
// Student() {} // Default constructor
}
// This will cause compilation error
// Student s = new Student(); // Error: No default constructor available
// This works
Student s = new Student("Alice");
14. How to Call a Super Class Constructor from a Constructor?
Use super() to call the superclass constructor. It must be the first statement in the constructor.
class Animal {
String name;
Animal(String name) {
this.name = name;
}
}
class Dog extends Animal {
String breed;
Dog(String name, String breed) {
super(name); // Call to superclass constructor
this.breed = breed;
}
void display() {
System.out.println("Name: " + name + ", Breed: " + breed);
}
}
Dog myDog = new Dog("Buddy", "Golden Retriever");
myDog.display(); // Output: Name: Buddy, Breed: Golden Retriever
15. IS-A Relationship
IS-A is a way of saying: This object is a type of that object. It's the core concept of inheritance.
// IS-A relationship examples
class Vehicle {}
class Car extends Vehicle {} // Car IS-A Vehicle
class Truck extends Vehicle {} // Truck IS-A Vehicle
class SportsCar extends Car {} // SportsCar IS-A Car and IS-A Vehicle
// Testing IS-A relationship
Car myCar = new Car();
System.out.println(myCar instanceof Vehicle); // true
System.out.println(myCar instanceof Object); // true
SportsCar ferrari = new SportsCar();
System.out.println(ferrari instanceof Car); // true
System.out.println(ferrari instanceof Vehicle);// true
Key Points About IS-A Relationship
- IS-A is inheritance (class extends another class or implements an interface)
- It's a one-way relationship (a Car is a Vehicle, but not all Vehicles are Cars)
- It enables code reusability and polymorphism
- It's tested using the
instanceofoperator