Skip to main content

DAE CIT Java chapter No 7 Generics

 7. Generics

 7.1. What is Generic

Brief Explanation:Generics in Java allow you to create classes and methods that can work with different data types while maintaining type safety. They provide a way to parameterize the types used in a class or method, making the code more flexible and reusable.

Programming Example

Without generics:

Class Box {

    Private Object content;

    Public void setContent(Object content) {

        This.content = content;

    }

    Public Object getContent() {

        Return content;

    }

}

Public class Main {

    Public static void main(String[] args) {

        Box box = new Box();

        Box.setContent(“Hello, Generics!”); // Storing a String

        String message = (String) box.getContent(); // Need to cast to String

        System.out.println(message);

    }

}

With generics:

Class Box<T> {

    Private T content;

    Public void setContent(T content) {

        This.content = content;

    }

    Public T getContent() {

        Return content;

    }

}

Public class Main {

    Public static void main(String[] args) {

        Box<String> box = new Box<>(); // Specifying the type as String

        Box.setContent(“Hello, Generics!”); // Storing a String

        String message = box.getContent(); // No need to cast, already a String

        System.out.println(message);

    }

}

```

 7.2. Generic Class

Brief Explanation:

A generic class is a class that can work with multiple types. It is defined with one or more type parameters specified in angle brackets (`<>`). These type parameters act as placeholders for the actual types that will be used when creating an instance of the class.

Programming examples 

// Generic class: Box

Class Box<T> {

    Private T content;

    Public void setContent(T content) {

        This.content = content;

    }

    Public T getContent() {

        Return content;

    }

}

Public class Main {

    Public static void main(String[] args) {

        Box<Integer> intBox = new Box<>();

        intBox.setContent(42); // Storing an Integer

        int number = intBox.getContent(); // No need to cast, already an Integer

        Box<String> stringBox = new Box<>();

        stringBox.setContent(“Java Generics”); // Storing a String

        String message = stringBox.getContent(); // No need to cast, already a String

        System.out.println(“Number: “ + number);

        System.out.println(“Message: “ + message);

    }

}

```

7.3. Generic Method

A generic method is a method that can work with different types. It is defined with its own type parameters, separate from the class’s type parameters. Generic methods are particularly useful when the method needs to deal with types that are unrelated to the class’s generic type.

Programming examples 

// Generic class: Pair

Class Pair<T, U> {

    Private T first;

    Private U second;

    Public Pair(T first, U second) {

        This.first = first;

        This.second = second;

    }

    Public T getFirst() {

        Return first;

    }

    Public U getSecond() {

        Return second;

    }

}

Public class Main {

    // Generic method: printPair

    Public static <T, U> void printPair(Pair<T, U> pair) {

        T first = pair.getFirst();

        U second = pair.getSecond();

        System.out.println(“First: “ + first + “, Second: “ + second);

    }

    Public static void main(String[] args) {

        Pair<Integer, String> pair1 = new Pair<>(42, “Java”);

        Pair<String, Double> pair2 = new Pair<>(“Generics”, 3.14);

        printPair(pair1);

        printPair(pair2);

    }

}

In this example, we have a generic class `Pair` that can hold two different types (`T` and `U`). Additionally, we have a generic method `printPair` that can work with different types of `


Comments

Popular posts from this blog

Short Q&A about constructors

  Q1: What is a constructor in Java, and when is it called? A1: A constructor in Java is a special method used to initialize objects. It is called when an instance of a class is created, allocating memory for the object in RAM. Q2: What happens if a class in Java does not have any constructor defined? A2: If a class in Java doesn't have any constructor defined, the Java compiler provides a default constructor by default. Q3: What are the two types of constructors in Java? A3: There are two types of constructors in Java:  1. No-arg constructor (Default constructor) 2. Parameterized constructor Q4: What are the rules for creating a Java constructor? A4: The rules for creating a Java constructor are as follows: - Constructor name must be the same as its class name. - A constructor must have no explicit return type. - A Java constructor cannot be abstract, static, final, or synchronized. Q5: What are the different access modifiers that can be used while declaring a constructor in ...

Chapter No 2 Java DAE CIT

  . Variable and Operators 1.1. Variable: Define: A variable is a named storage location in a program that holds data, and its value can be changed during the execution of the program. Syntax: datatype variableName; Explanation: Variables are used to store and manipulate data in a program. They have a data type that defines the kind of data they can hold, such as int, float, char, etc. Code int age; // Declaration of an integer variable age = 25; // Initialization of the variable with a value 1.2. Create Instance of a Variable: Define: Creating an instance of a variable involves declaring and optionally initializing a variable in a program. Syntax: datatype variableName = value; Explanation: This creates a variable and assigns an initial value to it at the time of declaration. score = 95.5  # Declaration and initialization of a floating-point variable 1.3. Use Preemptive Data Types: Define: Preemptive data types are data types that are predefined and provided by...

Chapter No 6 Interface Java

  Chapter 6                      Interfaces   6.1 Introduction  6.2. Defining and Implementing Interfaces   6.3. Advantages of using Interface    6.1 Introduction   An interface in Java is a collection of abstract methods. It provides a way to achieve abstraction and multiple inheritance in Java. An interface is a blueprint for a class and allows the definition of methods without specifying the implementation. Classes implementing an interface must provide concrete implementations for all its methods.   Syntax   interface MyInterface{ {      // Declare methods (implicitly public and abstract)      void method1();      void method2(); }   Explanation   An interface is declared using the interface keyword.  Methods declared in the interface ar...