Introduction to Java Class:

A Java class is a simple blueprint or template used to create objects. It defines the structure and behavior of objects by combining two main things: attributes and methods. Attributes, also called fields or variables, describe the properties of an object, such as its name, age, or color.

Methods define the actions an object can perform, like displaying information or performing calculations. By using classes, programmers can organize their code better, reuse it easily, and make it easier to manage. Java classes also support key object-oriented concepts like encapsulation (keeping data and behavior together), inheritance (reusing code from other classes), and polymorphism (objects behaving differently based on context). In short, a class describes what an object should be like and what it should do. For example, “Student” can be a class, and a specific student named “Ravi” is an object created from that class.


Properties of Java Classes:

The Properties of Java classes are explained below

  1. A Java class acts as a template or blueprint used to create objects. Each object created from a class will have the same structure and behavior defined in that class.
  2. A class combines data (fields or variables) and behavior (methods or functions) into one unit. This helps keep related information and actions together.
  3. Classes can have different access levels using modifiers like public, private, or protected. These define where the class and its members can be accessed from.
  4. A class can have constructors, which are special methods used to initialize objects when they are created.
  5. A Java class can inherit features from another class using the extends keyword. This helps in reusing code and building a class hierarchy.
  6. Java classes support polymorphism, allowing the same method to behave differently depending on the object that calls it.
  7. A class can be abstract, meaning it cannot be used to create objects directly but can provide a base for other classes to build upon.
  8. Classes can have instance members (specific to each object) and static members (shared across all objects of the class).Java classes are grouped into packages, which help organize code and avoid name conflicts.
  9. Classes help in creating modular code, where each class handles a specific task. This makes the code more reusable and easier to maintain.

Syntax and Declaration of Java Classes:

Types of Classes in Java

In Java, classes are broadly classified into two main types:

1. Built-in Classes:
These are the classes that come pre-defined in the Java API (Application Programming Interface). They are already available in the Java libraries and can be used directly by importing the required package. Examples of built-in classes are String, Scanner, ArrayList, Math, etc. For instance, the Scanner class is used to take input from the user, and the Math class is used for mathematical operations like square root, power, and trigonometric functions.

Example:

import java.util.Scanner;

class Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine(); // Using built-in class Scanner
System.out.println("Hello " + name);
}
}

2. User-defined Classes:
These are the classes that are created by programmers according to the requirements of the program. A user-defined class acts as a blueprint for creating objects and can contain fields, methods, and constructors. This type of class is helpful when you need to represent real-world entities in code, such as Car, Student, or Employee.

Example:

 
class Student {
    String name;
    int age;
    void display() {
        System.out.println("Name: " + name + ", Age: " + age);
    }

    public static void main(String[] args) {
        Student s = new Student();  // Creating object of user-defined class
        s.name = "Rahul";
        s.age = 20;
        s.display();
    }
}

Java Object: 


In Java object is a fundamental unit of Object-Oriented Programming (OOP). It is an instance of a class, meaning it is created from a class blueprint. An object represents a real-world entity and has both state (properties/fields) and behavior (methods).

For example, in real life a Car is an object with properties like color, brand, speed, and behaviors like driving, braking, and honking. Similarly, in Java programming, we create objects to model such entities.

Creating Objects in Java

Objects are created using the new keyword and a constructor
ClassName objectName = new ClassName();
example: 
class Car {
void drive() {
System.out.println("Car is driving...");
}

public static void main(String[] args) {
Car myCar = new Car(); // Object creation
myCar.drive(); // Calling method using object
}
}

Initialization of Object in Java

After creating an object in Java, we need to initialize it so that its fields (variables) get values before use. Java provides different ways to initialize an object.

1. Initialization using Reference Variable: We directly assign values to object fields using the dot (.) operator.
Example:

class Student {
String name;
int age;
}
class Test {
public static void main(String[] args) {
Student s1 = new Student(); // Object creation
s1.name = "Rahul"; // Initialization
s1.age = 20;
System.out.println("Name: " + s1.name + ", Age: " + s1.age);
}
}

2. Initialization using Methods: We can define a setter method inside a class to initialize object values.Example:

class Student {
String name;
int age;

void setData(String n, int a) {
name = n;
age = a;
}

void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

class Test {
public static void main(String[] args) {
Student s1 = new Student();
s1.setData("Rahul", 20); // Initialization via method
s1.display();
}
}

Constructors in Java:

In Java, a constructor is a special method that is used to initialize objects. It is automatically called when an object of a class is created. A constructor has the same name as the class and does not have a return type (not even void).

Characteristics of Constructors

  1. The constructor name must be the same as the class name.
  2. It is invoked automatically when an object is created.
  3. Constructors do not have a return type.
  4. They are mainly used to initialize object variables.
  5. If no constructor is defined, Java provides a default constructor automatically.

Types of Constructors in Java:

There are 3 types of construction in Java programming, and these are default, Parameterized, and copy construction.

1. Default Constructor

A default constructor is a constructor with no parameters. It initializes objects with default values. If no constructor is defined in a class, the Java compiler automatically provides a default constructor. Example:

class Car {
Car() { // Default constructor
System.out.println("Default Constructor called");
}
public static void main(String[] args) {
Car c = new Car(); // Calls default constructor
}
}

2. Parameterized Constructor

A parameterized constructor is a constructor that accepts arguments (parameters) to initialize object fields with specific values at the time of creation. Example:

class Student {
String name;
int age;
Student(String n, int a) { // Parameterized constructor
name = n;
age = a;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
Student s1 = new Student("Rahul", 20); // Passing values
s1.display();
}
}

3. Copy Constructor

A copy constructor is a constructor that creates a new object by copying the values of another object. Java does not provide it by default, but programmers can define it manually. Example:

class Student {
String name;
int age;
Student(String n, int a) {
name = n;
age = a;
}
Student(Student s) { // Copy constructor
name = s.name;
age = s.age;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
Student s1 = new Student("Rahul", 20);
Student s2 = new Student(s1); // Copy constructor
s2.display();
}
}

Constructor Overloading in Java:

In Java, constructor overloading is a feature that allows a class to have more than one constructor with the same name but different parameter lists (number or type of parameters). It is a way to create objects in multiple ways and initialize them differently. Constructor overloading is similar to method overloading, but it applies specifically to constructors.

Features of Construction Overloading:

  • All constructors in a class have the same name as the class.
  • Constructors must differ in their parameter list (number, type, or both).
  • Overloaded constructors help create objects with different initial states.
  • The correct constructor is called automatically based on the arguments passed during object creation.

Example of Constructor Overloading

class Student {
String name;
int age;
// Default constructor
Student() {
name = "Unknown";
age = 0;
}
// Parameterized constructor (1 parameter)
Student(String n) {
name = n;
age = 0;
}
// Parameterized constructor (2 parameters)
Student(String n, int a) {
name = n;
age = a;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
Student s1 = new Student(); // Calls default constructor
Student s2 = new Student("Rahul"); // Calls constructor with 1 parameter
Student s3 = new Student("Rita", 22); // Calls constructor with 2 parameters
s1.display();
s2.display();
s3.display();
}
}

Inheritance in Java: 

Inheritance is one of the core concepts of Object-Oriented Programming (OOP) in Java. In Java, inheritance is a mechanism where one class acquires the properties and behaviors (fields and methods) of another class. It is an important concept of Object-Oriented Programming (OOP) that promotes code reusability and method overriding.

Java supports the following types of inheritance:

1. Single Inheritance: Single inheritance is a type of inheritance where one derived class (child class) inherits from only one base class (parent class). It allows the child class to use the variables and methods of its parent class.

Declaration of Single Inheritance in Java

class A
{
  //methods and fields
}
Class B extends A
{
  //methods and fields
Example
// Create a base class or superclass. 
public class A 
{ 
// Declare an instance method. 
public void methodA() 
{ 
System.out.println("Base class method"); 
} 
} 
// Declare a derived class or subclass and extends class A. 
public class B extends A 
{ 
public void methodB() 
{ 
System.out.println("Child class method"); 
} 
} 
public class Myclass { 
public static void main(String[] args) 
{ 
// Create an object of class B. 
B obj = new B(); 
obj.methodA(); 
obj.methodB(); 
} 
}

2. Multilevel Inheritance:

In multilevel inheritance, a class inherits from a parent class, and then another class inherits from that child class, forming a chain. This helps in creating a hierarchy of classes. It allows derived classes to access properties and methods from all ancestor classes. The syntax of multi-level inheritance is

multilevel-inheritance-in-java

class A {
}
class B extends A {
}
class C extends B {
}

Here’s a simple Java program demonstrating multilevel inheritance:

class A {
void displayA() {
System.out.println("This is class A");
}
}
class B extends A {
void displayB() {
System.out.println("This is class B");
}
}
class C extends B {
void displayC() {
System.out.println("This is class C");
}
}
public class Test {
public static void main(String[] args) {
C obj = new C();
obj.displayA();
obj.displayB();
obj.displayC();
}
}

3. Multiple Inheritance in Java:

multiple-inheritance-in-java

In Multiple Inheritance, one child or subclass class can have more than one base class or superclass and inherit features from every parent class which it inherits. We have already discussed that Java does not support multiple inheritance with classes. We can achieve multiple inheritances only with the help of Interfaces. In the following diagram, Class C inherits from interfaces A and B.

Declaration (Using Classes – Not Allowed in Java) Java does not allow this:

class A {
void displayA() {
System.out.println("Class A");
}
}
class B {
void displayB() {
System.out.println("Class B");
}
}
// ❌ Not allowed: class C extends A, B
class C extends A, B { // ❌ Compilation error in Java
void displayC() {
System.out.println("Class C");
}
}

Correct Way: Using Interfaces: To achieve multiple inheritance, use interfaces:

interface A {
void displayA();
}
interface B {
void displayB();
}
class C implements A, B {
public void displayA() {
System.out.println("Interface A");
}
public void displayB() {
System.out.println("Interface B");
}
void displayC() {
System.out.println("Class C");
}
}
public class Main {
public static void main(String[] args) {
C obj = new C();
obj.displayA();
obj.displayB();
obj.displayC();
}
}

Hybrid Inheritance in Java: hybrid-inheritance-in-java

Hybrid inheritance is a combination of two or more types of inheritance (like single, multiple, multilevel, or hierarchical). It is designed to model complex relationships between classes. However, Java does not support hybrid inheritance using classes directly because Java does not support multiple inheritance with classes (to avoid ambiguity). But Java does support hybrid inheritance using interfaces.

Why Java Doesn’t Support Hybrid Inheritance with Classes?
To avoid problems like the Diamond Problem, Java restricts multiple inheritance of classes. But you can achieve hybrid inheritance by combining classes and interfaces.

Example:

// Base class
class A {
void displayA() {
System.out.println("Class A");
}
}
// Single inheritance: Class B inherits Class A
class B extends A {
void displayB() {
System.out.println("Class B");
}
}
// Interface C
interface C {
void displayC();
}
// Hybrid inheritance: Class D extends B and implements Interface C
class D extends B implements C {
public void displayC() {
System.out.println("Interface C");
}
void displayD() {
System.out.println("Class D");
}
}
public class Main {
public static void main(String[] args) {
D obj = new D();
obj.displayA(); // From class A
obj.displayB(); // From class B
obj.displayC(); // From interface C
obj.displayD(); // From class D
}
}

Question 1 Single Inheritance:

1. Create two classes: Animal with a method sound(),Dog that extends Animal and overrides the sound() method. Then, create an object of Dog and call the method.

class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound(); // Calls the overridden method
}
}

Question 2. multilevel inheritance

2. Create three classes:

  • Person → has a method display()
  • Employee → extends Person
  • Manager → extends Employee

Use multilevel inheritance to call the method from the top-most class using an object of the bottom-most class.

class Person {
void display() {
System.out.println("This is a person.");
}
}
class Employee extends Person {
void job() {
System.out.println("This person is an employee.");
}
}
class Manager extends Employee {
void role() {
System.out.println("This employee is a manager.");
}
}
public class Main {
public static void main(String[] args) {
Manager m = new Manager();
m.display(); // From Person
m.job(); // From Employee
m.role(); // From Manager
}
}

Question 3: Hierarchical Inheritance

Create a base classVehicle, two derived classes, Car and Bike. Each class should have its own method and access the base method.

class Vehicle {
void start() {
System.out.println("Vehicle starts");
}
}
class Car extends Vehicle {
void drive() {
System.out.println("Car is driving");
}
}
class Bike extends Vehicle {
void ride() {
System.out.println("Bike is riding");
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.start();
car.drive();
Bike bike = new Bike();
bike.start();
bike.ride();
}
}

Assignment:

Constructor Questions

  1. Write a Java program to create a class Employee with a constructor to initialize id, name, and salary. Create an object and display the details.
  2. Write a program to create a class Book with attributes title and author. Use a parameterized constructor to set values and display them.
  3. Create a class Circle with attributes radius. Use a constructor to initialize the value of radius and include a method to calculate the area.
  4. Write a program to create a class Laptop with attributes brand and price. Use a default constructor to assign values and display them.
  5. Create a class Teacher with two constructors (constructor overloading):
  6. One constructor accepts name and subject.
  7. Another constructor accepts name, subject, and salary.
    Demonstrate both constructors in the main method.

Inheritance Questions

  1. Write a Java program to create a base class Person with attributes name and age, and a derived class Student with additional attribute marks. Display details using inheritance.
  2. Create a class Animal with a method sound(). Derive classes Dog and Cat that override the sound() method. Demonstrate method overriding.
  3. Write a program where class Vehicle is the parent class and Car is the child class. Add attributes like brand in Vehicle and model in Car. Display details using inheritance.
  4. Create a base class Shape with method area(). Derive classes Rectangle and Circle that implement their own version of area() method.
  5. Write a Java program with a parent class Bank and child classes SavingAccount and CurrentAccount. Each child class should have its own method to display account type.

 

Compiled by Er. Basant Kumar Yadav

error: Content is protected !!
Scroll to Top