Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Friday, February 28, 2025

Object cloning, Inner classes


In Java, the final keyword can be used with classes, methods, and variables to restrict their behavior.

1. Final Class

A class declared as final cannot be inherited by any other class. This is useful when you want to prevent modifications to the class by subclassing.

Example:

final class FinalClass {

    void display() {

        System.out.println("This is a final class.");

    }

}

 

// This will cause an error because FinalClass cannot be inherited

// class SubClass extends FinalClass {} // Compilation error


2. Final Method

A method declared as final cannot be overridden in a subclass. This is useful when you want to prevent specific behavior from being changed.

Example:

class Parent {

    final void show() {

        System.out.println("This is a final method.");

    }

}

 

class Child extends Parent {

    // void show() {  // This will cause a compilation error

    //    System.out.println("Trying to override.");

    // }

}

In the example above, if you try to override the show() method in the Child class, it will result in a compilation error.

 

 

 

Inner Classes in Java

An inner class in Java is a class that is defined within another class. Inner classes have access to the members (including private members) of the outer class, making them useful for encapsulation and logically grouping related functionality.


Types of Inner Classes

1. Member Inner Class

A member inner class is a non-static class defined inside another class. It can access all members of the outer class, including private ones.

Example:

class Outer {

    private String message = "Hello from Outer class";

 

    // Inner class

    class Inner {

        void display() {

            System.out.println(message); // Can access private members of Outer class

        }

    }

 

    public static void main(String[] args) {

        Outer outer = new Outer();

        Outer.Inner inner = outer.new Inner(); // Creating an instance of inner class

        inner.display();

    }

}


2. Static Nested Class

A static nested class is a static member of the outer class. Unlike member inner classes, it cannot access non-static members of the outer class directly.

Example:

class Outer {

    static String message = "Static Nested Class Example";

 

    // Static nested class

    static class Nested {

        void display() {

            System.out.println(message); // Can access static members of Outer class

        }

    }

 

    public static void main(String[] args) {

        Outer.Nested nested = new Outer.Nested(); // No need to create an instance of Outer

        nested.display();

    }

}


3. Local Inner Class

A local inner class is defined within a method or a block and can only be accessed within that method/block.

Example:

class Outer {

    void outerMethod() {

        class LocalInner {

            void display() {

                System.out.println("Inside Local Inner Class");

            }

        }

        LocalInner inner = new LocalInner();

        inner.display();

    }

 

    public static void main(String[] args) {

        Outer outer = new Outer();

        outer.outerMethod();

    }

}


4. Anonymous Inner Class

An anonymous inner class is a class without a name, typically used when instantiating an interface or an abstract class.

Example using an interface:

interface Greeting {

    void sayHello();

}

 

class Main {

    public static void main(String[] args) {

        Greeting greet = new Greeting() {

            public void sayHello() {

                System.out.println("Hello from Anonymous Inner Class");

            }

        };

        greet.sayHello();

    }

}


Key Points

  • Member Inner Class: Non-static class inside another class, can access all members of the outer class.
  • Static Nested Class: A static class inside another class, can only access static members of the outer class.
  • Local Inner Class: Defined inside a method, only accessible within that method.
  • Anonymous Inner Class: A class without a name, mainly used to implement interfaces or extend abstract classes in a concise way.

 


Object Cloning 

Object Cloning in Java

In Java, object cloning refers to the process of creating an exact copy of an existing object. It is used when we want a replica of an object with the same state (field values) but stored in a different memory location. Java provides a built-in mechanism for cloning objects through the Cloneable interface and the clone() method defined in the Object class.


1. Need for Object Cloning

In object-oriented programming, there are situations where:

  • We need a duplicate object without calling the constructor explicitly.

  • We want to copy one object’s state into another without writing boilerplate setter methods.

  • We are dealing with prototypes in design patterns.


2. The Cloneable Interface

  • Located in the java.lang package.

  • It is a marker interface, meaning it does not have any methods.

  • If a class does not implement Cloneable and tries to call the clone() method, Java throws CloneNotSupportedException.


3. The clone() Method

  • Defined in the Object class.

  • Its general signature is:

    protected Object clone() throws CloneNotSupportedException
  • Since it's protected, we must override it in our class to make it accessible.


class Student implements Cloneable {

    int id;

    String name;


    // Overriding clone() and making it public

    public Object clone() throws CloneNotSupportedException {

        return super.clone();

    }

}


class StudentTest {

    public static void main(String[] args) {

        try {

            Student s1 = new Student();

            s1.id = 101;

            s1.name = "Krishna";


            // Cloning s1 into s2

            Student s2 = (Student) s1.clone();


            // Printing both objects

            System.out.println("Original Object: " + s1.id + " " + s1.name);

            System.out.println("Cloned Object  : " + s2.id + " " + s2.name);


        } 

catch (CloneNotSupportedException e) 

{

            System.out.println("Cloning not supported!");

        }

    }

}


No comments:

Post a Comment