0% found this document useful (0 votes)
24 views45 pages

JAVA UNIT-2 - Final

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views45 pages

JAVA UNIT-2 - Final

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Unit II: Class Hierarchy & Data Hiding

Property, Method, Constructor, Inheritance (IS-A) , Aggregation and Composition

(HAS-A), this and super, static and initialize blocks, Method overloading and

overriding, static and final keywords, Types of Inheritance, Compile time and

Runtime Polymorphism, Access Specifiers and scope, packages and access modifiers,

Abstract class, Interface, Interface Inheritance, Achieving Multiple Inheritance, Class

casting, Object Cloning, Inner Classes.

Property or Variable or Attribute or Class member

Variables are used for storing values.

There are different types of variables, for example:

 String - stores text, such as "Hello". String values are surrounded by double quotes
 int - stores integers without decimals, such as 123 or -123
 float - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
 boolean - stores values with two states: true or false.

Syntax:

< data Type><variable name> = <value>

Rules of declaring variable


 A variable name can consist of Capital letters A-Z, lowercase letters a-z, digits 0-9, and two special
characters such as underscore and dollar Sign.
 The first character must be a letter.
 Blank spaces cannot be used in variable names.
 Java keywords cannot be used as variable names.
 Variable names are case-sensitive.

Method

A method is a collection of statements that perform some specific task

Methods allow us to reuse the code without retyping the code.


Syntax of method

The return type : The data type of the value returned by the method or void if does not return a value.

Method Name : Name of the method

Parameter list : parameters are separated by comas

Method body : it is enclosed between braces

MethodOverloading.java

class MethodOverloading
{
void add(int a,int b)
{
int c=a+b;
System.out.println(c);
}

void add(float a,float b)


{
float c=a+b;
System.out.println(c);
}

void add(double a,double b)


{
double c=a+b;
System.out.println(c);
}
public static void main(String args[])
{
MethodOverloading m=new MethodOverloading();
m.add(10,20);
m.add(10.5,34.6);
m.add(1.3f,3.4f);
}
}
Output

javac MethodOverLoading.java

java MethodOverloading

30

45.1

4.7

Constructor

Constructors are meant for initializing the object. Constructor is a special type of method that is used to
initialize object values.

Constructor is invoked at the time of object creation. It constructs the values i.e. data for the object that is
why it is known as constructor.

Constructor is just like the instance method but it does not have any explicit return type.

Constructor name must be same as its class name.


Constructor should not return any value even void also.

Constructors are called automatically whenever an object is cereating.

Types of Constructors:
There are two types of constructors:-
1. Default constructor (no-argument constructor)
2. Parameterized constructor

1. Default constructor (no-argument constructor):-

A constructor is one which will not take any parameter.

A constructor that have no parameter is known as default constructor.

Syntax:-

class < class name >

classname() //default constructor


{

Block of statements;

...................;

...................;

..................;

..................;

};

2. Parameterized Constructor:- A constructor is one which takes some parameters.

Syntax:-

class < class name >

classname(list of parameters) //paramiterized constructor

Block of statements;

...................;

...................;

..................;

..................;

};

Constructor overloading is a technique in Java in which a class can have any number of constructors
such that each constructor differ with their parameters

Constructors with diff arguments is known as Constructor Overloading

Constructor over loading example

Student.java

class Student
{
int rollNumber;
String branchName;
Student()
{
rollNumber=100;
branchName="CSE";
System.out.println(rollNumber);
System.out.println(branchName);
}
Student(int rollNumber)
{
this.rollNumber=rollNumber;
branchName="CSE";
System.out.println(rollNumber);
System.out.println(branchName);

}
Student(int rollNumber,String branchName)
{
this.rollNumber=rollNumber;
this.branchName=branchName;
System.out.println(rollNumber);
System.out.println(branchName);

}
public static void main(String args[])
{
Student ravi=new Student();
System.out.println("-----------");
Student seetha=new Student(101);
System.out.println("-----------");
Student balu=new Student(102,"CSE");

}
Output

javac Student.java
java Student
100
CSE
-----------
101
CSE
-----------
102
CSE
Inheritance: The process of taking the features(data members and class) from one class to
another class is known as inheritance
The class which is giving the features is known as base/parentclass.
The class which is taking the features is known as derived/child/subclass.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Advantages of INHERITANCE:
I. Application development time is veryless.
II. Redundancy (repetition) of the code is reducing. Hence we can get less memory cost and
consistent results.

Types of INHERITANCES

Based on taking the features from base class to the derived class, in JAVA we have five types of
inheritances. They are as follows:

Single Inheritance : In single inheritance, subclasses inherit the features of one superclass. In
image below, the class A serves as a base class for the derived class B.

Heirarcial Inheritance

In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one sub
class.In below image, the class A serves as a base class for the derived class B,C and D.
Multilevel Inheritance :

In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the
derived class also act as the base class to other class. In below image, the class A serves as a base
class for the derived class B, which in turn serves as a base class for the derived class C.

Multiple Inheritance : In Multiple inheritance ,one class can have more than one superclass
and inherit features from all parent classes.

Java does not support multiple inheritance with classes.

In java, we can achieve multiple inheritance only through Interfaces.

In image below, Class C is derived from class A and B.


Hybrid Inheritance: It is a mixture of two or more of the above types of inheritance.

Since java doesn’t support multiple inheritance with classes, the hybrid inheritance is also not
possible with classes.

In java, we can achieve hybrid inheritance only through Interfaces.

Singleinheritance.java

class Mobile_Version1

void smsservice()

System.out.println("sms service");
}

void callingservice()

System.out.println(" calling service");

class Mobile_Version2 extends Mobile_Version1

void cameraservice()

System.out.println("camera service");

class Single_inheritance

public static void main(String args[])

Mobile_Version2 m=new Mobile_Version2();

System.out.println("Calling Mobile_Version1 class methods through Mobile_Version2 object ");

m.cameraservice();

m.smsservice();

m.callingservice();

Output

Calling Mobile_Version1 class methods through Mobile_Version2 object


camera service

sms service

calling service

Heirarcial Inheritance

In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one sub
class.In below image, the class A serves as a base class for the derived class B,C and D.

Heirarcial_inheritance.java

class MobileVersion1

void smsservice()

System.out.println("sms service");

void calling_service()

System.out.println("calling service");

}
class MobileVersion2 extends MobileVersion1

voidcameraservice()

System.out.println("camera service");

class MobileVersion3 extends MobileVersion1

voidfingerprint_service()

System.out.println("finger print service");

class MobileVersion4 extends MobileVersion1

void facerecognization_service()

System.out.println("facerecognization service");

class Heirarcial_inheritance

public static void main(String args[])

{
MobileVersion1 m1=new MobileVersion1();

System.out.println("mobile version1 services");

m1.calling_service();

m1.smsservice();

MobileVersion2 m2=new MobileVersion2();

System.out.println("\nmobile version2 services:-");

m2.calling_service();

m2.smsservice();

m2.cameraservice();

MobileVersion3 m3=new MobileVersion3();

System.out.println("\nmobile version3 services:-");

m3.calling_service();

m3.smsservice();

m3.fingerprint_service();

MobileVersion4 m4=new MobileVersion4();

System.out.println("\nmobile version4 services:-");

m4.calling_service();

m4.smsservice();

m4.facerecognization_service();

Output

javac Heirarcial_inheritance.java
javaHeirarcial_inheritance

mobile version1 services

calling service

sms service

mobile version2 services:-

calling service

sms service

camera service

mobile version3 services:-

calling service

sms service

finger print service

mobile version4 services:-

calling service

sms service

facerecognization service

This Keyword

The main purpose of using this keyword is to differentiate the formal parameter and class members of
class, whenever the formal parameter and data members of the class are similar then jvm get ambiguity

To differentiate between formal parameter and data member of the class, the data member of the
class must be preceded by "this".

"this" keyword can be use in two ways.

 this .variablename-this is used for calling current class variable


 this() (this is used for calling current class constructor
 this.methodname()-this is used to call current class method

It can be used to refer current class instance variable.


this() can be used to invoke current class constructor.
It can be used to invoke current class method (implicitly)

Student.java

class Student

int rollNumber;

String branchName;

Student(int rollNumber,String branchName)

this.rollNumber=rollNumber;

this.branchName=branchName;

public static void main(String args[])

Student s1=new Student(100,"CSE");

System.out.println(s1.rollNumber);

System.out.println(s1.branchName);

javac Student.java

java Student

100

CSE

Super Keyword

Super keyword is placing an important role in three places. They are at variable level, at method
level and at constructor level.
Super at variable level
Whenever we inherit the base class variables into derived class, there is a possibility that
base class variables are similar to derived class members.
In order to distinguish the base class variables with derived class variables in the derived
class, the base class members will be preceded by a keyword super.

Syntax for super at variable level super.variablename;


Super at method level
Whenever we inherit the base class methods into the derived class, there is a possibility that
base class methods are similar to derived methods.
To differentiate the base class methods with derived class methods in the derived class, the
base class methods must be preceded by a keyword super.
Syntax for super at method level: super.methodname();

Super at Constructor Level

super keyword can also be used to invoke the parent class constructor

Syntax super();

MobileVersion2.java

class MobileVersion1

String modelName="Nokia1600";

int price=2000;

public void display()

System.out.println("MobileVerison1 features");

System.out.println(modelName);

System.out.println(price);

class MobileVersion2 extends MobileVersion1

String modelName="Redmi 10";

int price=10000;
public void display()

System.out.println("MobileVerison2 features");

System.out.println(modelName);

System.out.println(price);

System.out.println("MobileVerison1 features");

System.out.println(super.modelName);

System.out.println(super.price);

super.display();

public static void main(String args[])

MobileVersion2 m1=new MobileVersion2();

m1.display();

javac MobileVersion2.java

java MobileVersion2

MobileVerison2 features

Redmi 10

10000

MobileVerison1 features

Nokia1600
2000

MobileVerison1 features

Nokia1600

2000

Association

Association is relation between two separate classes which establishes through their Objects. Association
can be one-to-one, one-to-many, many-to-one, many-to-many.
Two forms of Associations are Composition and Aggregation

Aggregation is a kind of association

Aggregation vs Composition

1. Dependency: Aggregation implies a relationship where the child can exist independently of the
parent. For example, Bank and Employee, delete the Bank and the Employee still exist. whereas
Composition implies a relationship where the child cannot exist independent of the parent.
Example: Human and heart, heart don’t exist separate to a Human
2. Type of Relationship: Aggregation relation is “has-a” and composition is “part-of” relation.

Aggregation Example (has a relation ship)

class Author

String authorName;

int age;

String place;

// Author class constructor

Author(String name, int age, String place)

this.authorName = name;

this.age = age;

this.place = place;

}
}

class Book

String name;

int price;

// author details

Author auther;

Book(String n, int p, Author auther)

this.name = n;

this.price = p;

this.auther = auther;

public static void main(String[] args) {

Author auther = new Author("John", 42, "USA");

Book b = new Book("Java for Begginer", 800, auther);

System.out.println("Book Name: "+b.name);

System.out.println("Book Price: "+b.price);

System.out.println("------------Auther Details----------");

System.out.println("Auther Name: "+b.auther.authorName);

System.out.println("Auther Age: "+b.auther.age);

System.out.println("Auther place: "+b.auther.place);

}
}

Output

javac Book.java

java Book

Book Name: Java for Begginer

Book Price: 800

------------Auther Details----------

Auther Name: John

Auther Age: 42

Auther place: USA

MethodOverRiding

When super class and sub class method has same name the subclass method overrides the super class
method isknown as method over riding

/*When super class and sub class contains

same method overriding super class method with the sub class

is knwon method over riding

*/

class MobileVersion1

public void hotSpot()

System.out.println("5 meters");

class MobileVersion2 extends MobileVersion1


{

public void hotSpot()

System.out.println("10 meters");

public static void main(String args[])

MobileVersion2 m=new MobileVersion2();

m.hotSpot();

Output

javac MobileVersion2.java

java MobileVersion2

10 meters

Static keyword

In Java, static keyword is mainly used for memory management. It can be used with variables,
methods, blocks and nested classes. It is a keyword which is used to share the same variable or method of
a given class.

Basically, static is used for a constant variable or a method that is same for every instance of a class.
The main method of a class is generally labeled static.

In order to create a static member (block, variable, method, nested class), you need to precede its
declaration with the keyword static. When a member of the class is declared as static, it can be accessed
before the objects of its class are created, and without any object reference.

Static block

Java supports a special block, called static block which can be used for static variable initializations of a
class. This code inside static block is executed only once. Static block calling before main method

Syntax
static

//static block

Static Variable

When you declare a variable as static, then a single copy of the variable is created and divided among
all objects at the class level. Static variables are global variables. Basically, all the instances of the class
share the same static variable. Static variables can be created at class-level only.

Generally Static variables are called by

Classname.variablename;

Static method

When a method is declared with the static keyword, it is known as a static method. The most common
example of a static method is the main( ) method.

We can access static methods using classname

Static methods can be called by classname.methodname()

Syntax

Classname.methodname();

Static keyword example

//static Block Level will execute before main

// static varaible can be called byclassname.variable

//staticmethod canbe called byclassname.methodname()

//static Block Level will execute before main

class AccountHolder

long accountNumber;
static String bankName="SBI";

static long pinCode=530016L;

static

System.out.println("library files loading");

static void pinCode()

System.out.println(pinCode);

public static void main(String args[])

System.out.println(AccountHolder.bankName);

AccountHolder.pinCode();

Output

javac AccountHolder.java

java AccountHolder

library files loading

SBI

530016

Polymorphism: Polymorphism in Java is a concept by which we can perform a single action in


different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly"
means many and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.

If you overload a static method in Java, it is the example of compile time polymorphism. Here,
we will focus on runtime polymorphism in java.

Static polymorphism or Compile time polymorphism or early binding

In static polymorphism method invocation is determined at compile time

Static polymorphism is known as early binding because method invocation is determined early by the
compiler at the compile time

StaticPolymorphism.java

class StaticPolymorphism

public static void add(int a ,int b)

int c=a+b;

System.out.println(c);

public static void add(double a,double b)

double c=a+b;

System.out.println(c);

public static void main(String args[])

StaticPolymorphism s=new StaticPolymorphism();

s.add(10,20);
s.add(10.4,23.5);

javac StaticPolymorphism.java

java StaticPolymorphism

30

33.9

Dynamic Polymorphism or run time polymorphism or late binding

method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.

dynamic polymorphism is known as late binding because method invocation is determined late at
runtime by the jvm.

Method Overriding is an example of Dynamic polymorphism

MobileVersion2.java

class MobileVersion1

public void hotSpot()

System.out.println("5 meters");

class MobileVersion2 extends MobileVersion1

public void hotSpot()

{
System.out.println("10 meters");

public static void main(String args[])

MobileVersion2 m=new MobileVersion2();

m.hotSpot();

Output

javac MobileVersion2.java

java MobileVersion2

10 meters

Final Keyword
final keyword is used in different contexts. First of all, final is a non-access modifier applicable only to a
variable, a method or a class.Following are different contexts where final is used

Final variableWhen a variable is declared with final keyword, its value can’t be modified, essentially, a
constant.

Final_Variable.java

class Final_Variable
{

public static void main(String args[])

final int pi=3.14;

int a=20;//complete time error final variable cannot be reintiantiated

Output compile time error

Final method: when a method declared as final method cannot be overridden by the sub class

Final_Method.java

class MobileVersion1

final public void hotSpot()

System.out.println("5 meters");

class MobileVersion2 extends MobileVersion1

public void hotSpot()

System.out.println("10 meters");

public static void main(String args[])

MobileVersion2 m=new MobileVersion2();

m.hotSpot();

}
}

output

compile time error

MobileVersion2.java:15: error: hotSpot() in MobileVersion2 cannot override hotSpot() in


MobileVersion1

public void hotSpot()

overridden method is final

Final class: When ever a parent class declared as final class its child class or sub class cannot be inherit
the parent class

Child.java
final class Parent
{//parent class

}
class Child extends Parent

{//child class

public static void main(String args[])


{
Child c=new Child();
}
}

Output
javac Final_Class.java
java Final_Class
Compile time error
Final class cannot be inherited
Access modifiers or Access specifiers in java

Access specifiers define the boundary and scope to access the method, variable, and class etc. Java has
defines four type of access specifiers such as:-
1. public
2. private
3. protected
4. default

These access specifiers are defines the scope for variables/methods. If you are not defining any access
specifier so it will be as 'default' access specifier for variables/methods.

1. public access specifier:- The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
Ex:-
public int number;

2. private access specifier:-The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
3. protected access specifier:- The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be accessed from outside the
package.
4. default access specifier:- Actually, there is no default access modifier; the absence of a modifier is
treated as default. The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default..
Classes belonging to other packages cannot access. That is why default access modifier is known as
package level access.

Access within within outside package by subclass outside


Modifier class package only package

Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

Package:Package is a collection of similar classes,interfaces, and sub packages


simply package is a directory or folder

uses of packages are

1) Java package is used to categorize the classes

and interfaces so that they can be easily maintained.

2) Java package provides access protection.

Types of packages

There are two types of packages are there

in java

1.built in packages:

2. user defined packages

Built in packages: these are predefined packages

which are present after installing jdk

example

import java.io.*;

import java.applet.*

import java.sql.*;

user defined packages :these are defined by the user

creating user defined package

syntax:

package packagename;

how to compile package program in java

javac -d . filename.java

-d creates package
how to run package program

java packagename.classname

importing userdefined packages

1. Import packagename.*(imports allclasses in the package)


2. Import packagename.classname;(import particular class name)

CSE.java

package college;

class CSE

public static void main(String args[])

System.out.println("CSE is the branch is part of college");

output:

javac -d . CSE.java

java College.CSE

CSE is the branch is part of college

Abstract class:

Abstraction is a process of hiding the implementation details and showing only functionality to
the user.

There are two types of classes present in java


1.Concrete classes
2.Abstract classes
A concrete class is one which is containing fully defined methods or implemented method.

A class that is declared with abstract keyword, is known as abstract class.

It can have abstract and non-abstract methods.


It cannot be instantiated. We cannot create objects to abstract class
Abstract class can contain 0 or more abstract methods
We can achieve 0 to 100% abstraction using abstract class;
Syntax:
abstract class <classname>
{
}

Abstract methods: A method which is declared as abstract and does not have implementation is known as
an abstract method.An abstract method methodis an incomplete method

Abstract method syntax


abstract returntype methodname();

AbstractBankDemo.java

abstract class Bank

public abstract void getRateOfInterest();

public void withdraw(int balance,int debit)

int withdraw=balance-debit;

class SBI extends Bank

public void getRateOfInterest()

System.out.println("SBI Rate of interest is 6%");

}
}

class HDFC extends Bank

public void getRateOfInterest()

System.out.println("SBI Rate of interest is 8%");

class AbstractBankDemo

public static void main(String args[])

SBI s=new SBI();

s.getRateOfInterest();

HDFC h=new HDFC();

h.getRateOfInterest();

Output

javac AbstractBankDemo.java

java AbstractBankDemo

Interest rate of SBI 6%

Interest rate of HDFC 8%


Interface

Interface is similar to class which is collection of public static final variables (constants) and abstract

methods.

The interface is a mechanism to achieve fully abstraction in java. There can be only abstract methods in the

interface. It is used to achieve fully abstraction and multiple inheritance in Java.

 It is used to achieve fully abstraction(100% abstraction).

 By using Interface, you can achieve multiple inheritance in java.

 It is implicitly abstract. So we no need to use the abstract keyword when declaring an


interface.

 Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.

 Methods in an interface are implicitly public.

 All the data members of interface are implicitly public static final.

 You can not instantiate an interface which means we cannot create object directly to
interface.

 It does not contain any constructors.

 All methods in an interface are abstract.

 Interface can not contain instance fields. Interface only contains public static final
variables.

 Interface is can not extended by a class; it is implemented by a class.

 Interface can extend multiple interfaces. It means interface support multiple inheritance

Interface Syntax:

interface <interfacename>
{
public static final datatype variablename=value;
//Any number of final, static fields
abstract returntype methodname(list of parameters or no parameters);
//Any number of abstract method declarations
}

Rules for implementation interface

 A class can implement more than one interface at a time.

 A class can extend only one class, but implement many interfaces.

 An interface can extend another interface, similarly to the way that a class can extend another
class.
 Abstract class Interface

1) Abstract class can have abstract and non-abstract


Interface can have only abstract methods.
methods.

2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.

3) Abstract class can have final, non-final, static and


Interface has only static and final variables.
non-static variables.

4) The abstract keyword is used to declare abstract The interface keyword is used to declare
class. interface.

5) An abstract class can be extended using keyword An interface can be implemented using
"extends". keyword "implements".

6) A Java abstract class can have class members like Members of a Java interface are public by
private, protected, etc. default.

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).

How Multiple inheritance achieved in java


Child.java

interface Mother

public static final float height=5.2f;

public abstract void height();

interface Father

public static final float height=6.2f;

public abstract void height();

class Child implements Mother,Father

public void height()

System.out.println((Mother.height+Father.height)/2);

public static void main(String args[])

Child c=new Child();

c.height();

}
}

javac Child.java

java Child

5.7

Interface Inheritence

Interface extends another interface is known as interface inheritance

BankDemo.java

interface Bank

public abstract void withdrawService();

public abstract void depositService();

interface SBI extends Bank

public abstract void loanService();

class BankDemo implements SBI

public void withdrawService()

System.out.println("withdraw service implementation");

public void depositService()

System.out.println("deposit service implementation");


}

public void loanService()

System.out.println("loan service implementation");

public static void main(String args[])

BankDemo b=new BankDemo();

b.withdrawService();

b.depositService();

b.loanService();

output

javac BankDemo.java

java BankDemo

java BankDemo

withdraw service implementation

deposit service implementation

loan service implementation

Class Casting
A process of converting one data type to another is known as Typecasting
In java, there are two types of casting namely up casting and down casting as follows:
Upcasting

Assigning the object of subclass to parent class reference is known as Upcasting


Upcasting is done by the system implicitly

DownCasting

Downcasting: assigning the Object or object reference of super class to the sub class reference is
known as downcasting

Downcasting cannot done implicitly

Downcastingmust done by the programmer explicitly

Downcasting always need upcasting

ClassCasting.java

class Mobile

public void calling()

System.out.println("Calling from nokia 1600");

public void smsService()

System.out.println("smsservice");

class Samsung extends Mobile

public void camera()

System.out.println("camera");
}

class ClassCasting

public static void main(String args[])

System.out.println("Upcasting");

Samsung s=new Samsung();

Mobile m=s;//assigning child class referece to parentclass type

m.calling();

m.smsService();

System.out.println("Downcasting");

Mobile m1=new Samsung();

Samsung s1=(Samsung)m1;// assigning parent reference to sub class type

s1.camera();

s1.calling();

Output

javac ClassCasting.java

java ClassCasting

Upcasting

Calling from nokia 1600

smsservice
Downcasting

camera

Calling from nokia 1600

Object Cloning in java

The object cloning is a way to create exact copy of an object. The clone() method of Object
class is used to clone an object.

The java.lang.Cloneable interface must be implemented by the class whose object clone we
want to create. If we don't implement Cloneable interface, clone() method generates
CloneNotSupportedException.

The clone() method is defined in the Object class. Syntax of the clone() method is as follows:

1. protected Object clone() throws CloneNotSupportedException

Student.java

class Student implements Cloneable

String rollNumber;

int age;

Student(String rollNumber,int age)

this.rollNumber=rollNumber;

this.age=age;

public Object clone()throws CloneNotSupportedException

return super.clone();

}
public static void main(String args[])throws CloneNotSupportedException

Student s1=new Student("20kd1a1567",22);

System.out.println("S2 hash code="+s1.hashCode());

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

System.out.println(s2.rollNumber);

System.out.println(s2.age);

System.out.println("s2 hash code="+s2.hashCode());

OUTPUT

S2 hash code=746292446

20kd1a1567

22

s2 hash code=140435067

Nested Classes:

Java nested class is a class which is declared inside the another class.
We use inner classes to logically group classes in one place so that it can be more readable and
maintainable.

Nested class cannot exit independently without outer class

advantages:

nested classes enables you to group classes in a single pace.

It creates more read ability of the code.

There are two types of nested classes in java

1.Non Static nested class:

2.Static nested class

Non static nested class: non static inner class present inside outer class is known as Non static
nested class

Regular inner class or non static class object creation

Outer_Class outer = new Outer_Class();

Outer_Class.Inner_Class inner = outer.new Inner_Class();

NonStatic nested class again divided into three types

1.regular inner class:non static inner class present inside outer classknown as regualra inner class

Regular innerclass can access private,static,non static memebrs of outer class

2.local method inner class: inner class present inside local method of outer class is known as
local method inner class

3Anonymous inner class:inner class which has no name is known as Anonymous inner class

Static inner class static class present inside the outer class is known as static inner class

Static inner can can access only static members of outer class. It cannot access non static memebrs of
outer class
static class object creation

OuterClass.StaticNestedClass nestedObject =new OuterClass.StaticNestedClass();

Regular inner class example

Outer.java

class Outer

class Inner

public void m1()

System.out.println(" regular Innerclass method");

public static void main(String args[])

Outer o=new Outer();

Outer.Inner i=o.new Inner();

i.m1();

javac Outer.java

Java Outer

regular Innerclass method

Static nested class example


class OuterClass

static int x=10;

static class InnerClass

public void display()

System.out.println(x);

public static void main(String arg[])

OuterClass.InnerClass o=new OuterClass.InnerClass();

o.display();

java OuterClass.java

java OuterClass

10.

(3) Local method inner class:

class Outer{

public void outerMethod(){


int atmpin=1234;

class Inner{

public void inMethod(){

System.out.println("Method Inner class"+atmpin);

}//end of inner class

Inner inobj=new Inner();

inobj.inMethod();

}}

public class InnerMethodDemo{

public static void main(String[] args){

Outer outobj=new Outer();

outobj.outerMethod();

}}

You might also like