0% found this document useful (0 votes)
6 views39 pages

Module 2 - 3

The document provides an overview of nested classes in Java, detailing their types, including inner classes, method-local inner classes, anonymous inner classes, and static nested classes. It also covers garbage collection, its advantages, and how objects can become unreferenced, along with the finalize method and its role in cleanup. Additionally, the document discusses inheritance in Java, explaining the concepts of superclass and subclass, the use of the 'extends' keyword, and the 'super' keyword for accessing superclass members.

Uploaded by

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

Module 2 - 3

The document provides an overview of nested classes in Java, detailing their types, including inner classes, method-local inner classes, anonymous inner classes, and static nested classes. It also covers garbage collection, its advantages, and how objects can become unreferenced, along with the finalize method and its role in cleanup. Additionally, the document discusses inheritance in Java, explaining the concepts of superclass and subclass, the use of the 'extends' keyword, and the 'super' keyword for accessing superclass members.

Uploaded by

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

Inner class

Nested Classes Syntax


• Variables of a class too can
have another class as its the class Outer_Demo is the
member. outer class and the class
• Writing a class within another Inner_Demo is the nested class.
is allowed in Java.
• The class written within is class Outer_Demo {
called the nested class, and class Inner_Demo {
the class that holds the }
inner class is called the }
outer class.

2
Types of Nested class
Nested classes are
divided into two types
▷ Non-static nested
classes (Inner
class) − These are
the non-static
members of a class.

▷ Static nested
classes − These are
the static members
of a class. 3
Inner Classes (Non-static Nested
Classes)
▷ Inner classes are of three
▷ Inner classes are a security
types depending on how and
mechanism in Java.
where you define them. They
▷ Class cannot be associated are
with the access modifier
private, but if we have the
class as a member of other 1. Inner Class
class, then the inner class 2. Method-local Inner
can be made private. Class
3. Anonymous Inner
▷ And this is also used to Class
access the private
members of a class.
4
1. Inner Class
▷ Unlike a class, an inner class can be private and
public class My_class {
once you declare an inner class private, it cannot
be accessed from an object outside the class.
class Outer_Demo { public static void main(String args[]) {
int num; // Instantiating the outer class
// inner class Outer_Demo outer = new
Outer_Demo();
private class Inner_Demo {
public void print() {
// Accessing the display_Inner()
System.out.println("This is an inner
method.
class");
outer.display_Inner();
}
}
}
}
// Accessing he inner class from the method
within
void display_Inner() { Output
Inner_Demo inner = new Inner_Demo(); This is an inner class.
inner.print();
} 5
Accessing the Private
Members
public class My_class2 {
▷ Suppose, a class is having private members to
public static void main(String
access them. Write an inner class in it, return args[]) {
the private members from a method within the // Instantiating the outer class
inner class,
Outer_Demo outer = new
▷ Example Outer_Demo();
class Outer_Demo {
// private variable of the outer class // Instantiating the inner class
private int num = 175; Outer_Demo.Inner_Demo inner =
outer.new Inner_Demo();
// inner class
public class Inner_Demo { System.out.println(inner.getNum());
public int getNum() { }
System.out.println("This is the getnum method of the }
inner class");
return num;
Output
}
This is the getnum method of the
} inner class: 175 6
}
2. Method-local Inner Class
▷ It is possible to write a class within a method and
this will be a local type.
▷ Like local variables, the scope of the inner class is
restricted within the method.
▷ A method-local inner class can be instantiated only
within the method where the inner class is defined.

7
Example // Accessing the inner class
public class Outerclass { MethodInner_Demo inner = new
// instance method of the outer class MethodInner_Demo();

void my_Method() inner.print();

{ }

int num = 23;


// method-local inner class public static void main(String args[])

class MethodInner_Demo { {

public void print() Outerclass outer = new Outerclass();

{ outer.my_Method();

System.out.println("This is method inner }


class "+num); }
}
} // end of inner class
Output
This is method inner class 23
8
Anonymous Inner Class
abstract class AnonymousInner {
public abstract void mymethod();
▷ An inner class declared }
without a class name is public class Outer_class {
known as an anonymous
public static void main(String args[]) {
inner class.
Anonymous Inner inner = new Anonymous
▷ In case of anonymous inner Inner()
classes, we declare and
{
instantiate them at the
same time. public void mymethod() {
System.out.println("This is an example of
▷ Generally, they are used
anonymous inner class");
whenever you need to
override the method of a }

Outputclass or an interface };
This is an example of anonymous inner.mymethod();
inner class }
}
9
Static Nested Class
▷ A static inner class is a public class Outer
{
nested class which is a static static class Nested_Demo
member of the outer class. {
public void my_method()
▷ It can be accessed without {
instantiating the outer class, System.out.println("This is
my nested class");
using other static members. }
}
▷ Just like static members, a
static nested class does not public static void main(String
have access to the instance args[])
{
variables and methods of the Outer.Nested_Demo nested =
outer class. new Outer.Nested_Demo();
nested.my_method();
Output
}
This is my nested class
}
10
Java Garbage Collection
▷ garbage means unreferenced
objects.
Advantage of Garbage
Collection
▷ Garbage Collection is process
of reclaiming the runtime
unused memory
▷ It makes java memory efficient
automatically. In other words,
it is a way to destroy the because garbage collector removes
unused objects. the unreferenced objects from heap
memory.
▷ To do so, free() function is ▷ It is automatically done by the
used in C language and garbage collector(a part of JVM) so we
delete() in C++. don't need to make extra efforts.
▷ But, in java it is performed
automatically. So, java
provides better memory
management. 11
How can an object be
unreferenced?
There are many ways:

▷ By nulling the reference


▷ By assigning a
reference to another
▷ By anonymous object
etc.

12
Example

1. By nulling a reference:
Employee e=new Employee();
e=null;

2. By assigning a reference to another


Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;
//now the first object referred by e1 is available for garbage collectio
n

3. By anonymous object:
new Employee();
13
finalize() method
▷ The finalize() method is invoked each time before the object is garbage
collected.
▷ This method can be used to perform cleanup processing.
protected void finalize throws Throwable{}
▷ Since Object class contains the finalize method hence finalize
method is available for every java class.
▷ we can override this method to define our own clean-up activities.
gc() method
▷ The gc() method is used to invoke the garbage collector to perform
cleanup processing. The gc() is found in System and Runtime classes.
▷ public static void gc(){}

14
class Hello {
public static void main(String[] args)

Case 1a-Example
{
String s = new String("RR");
s = null;
▷ The object which is // Requesting JVM to call Garbage Collector
eligible for Garbage method
Collection, that System.gc();
object’s corresponding System.out.println("Main Completes");
class finalize method }
is going to be
// Here overriding finalize method
executed. public void finalize()
{
System.out.println("finalize method
overriden");
}

s = null and ‘s’ is the


object of String class, so Output:
String class finalize Main Completes
method is going to be
15
called and not our
class Hello {
public static void main(String[] args)

Case 1b-Example
{
Hello s = new Hello();
s = null;

// Requesting JVM to call Garbage Collector


method
System.gc();
System.out.println("Main Completes");
}

Hello class finalize // Here overriding finalize method


method is called. public void finalize()
{
System.out.println("finalize method
overriden");
}

Output:
finalize method overriden
Main Completes
16
class Bye {
public static void main(String[] args)

Case 2-Example
{
Bye m = new Bye();

▷ We can call finalize method Explicitly // Calling finalize method Explicitly.


then it will be executed just like normal m.finalize();
method call but object won’t be m.finalize();
m = null;
deleted/destroyed
Output: // Requesting JVM to call Garbage Collector
method
finalize method overriden System.gc();
//call by programmer but object won't System.out.println("Main Completes");
}
gets destroyed.
finalize method overriden // Here overriding finalize method
public void finalize()
//call by programmer but object won't {
gets destroyed. System.out.println("finalize method
finalize method overriden overriden");
}
Main Completes }
Output:
//call by Garbage Collector just before finalize method overriden
destroying the object. finalize method overriden
finalize method overriden 17
Case 3 a:
class Hi {
public static void main(String[] args)
{
▷ Part a) If programmer calls finalize Hi j = new Hi();
method, while executing finalize // Calling finalize method Explicitly.
method some unchecked exception j.finalize();
rises.
j = null;

Output: // Requesting JVM to call Garbage Collector


method
exception in thread "main" System.gc();
java.lang.ArithmeticException: System.out.println("Main Completes");
/ by zero followed by stack trace.. }

// Here overriding finalize method


public void finalize()
{
System.out.println("finalize method
overriden");
System.out.println(10 / 0);
}
}

18
Case 3b :
class RR {
public static void main(String[] args)
{
▷ If garbage Collector calls finalize RR q = new RR();
q = null;
method, while executing finalize
method some unchecked exception // Requesting JVM to call Garbage Collector
rises. method

System.gc();
System.out.println("Main Completes"); }
Output: // Here overriding finalize method
finalize method overriden public void finalize()
{
Main Completes System.out.println("finalize method
overriden");
System.out.println(10 / 0);
}
}

19
Inheritance
▷ Inheritance in Java is a mechanism in which one
object acquires all the properties and behaviors of a
parent object.
▷ It is an important concept in OOPs
▷ It ensures Method overriding and Code Reusability
▷ The class which inherits the properties of other is
known as subclass (derived class, child class)
▷ The class whose properties are inherited is known as
superclass (base class, parent class).

20
Inheritance
▷ Class: A class is a group of objects which have common properties. It
is a model from which objects are created.
▷ Sub Class/Child Class: Subclass is a class which inherits the other
class. It is also called a derived class, extended class, or child class.
▷ Super Class/Parent Class: Superclass is the class from where a
subclass inherits the features. It is also called a base class or a parent
class.
▷ Reusability: Reusability is a mechanism which enables you to reuse
the fields and methods of the existing class when you create a new
class. You can use the same fields and methods already defined in the
previous class.

extends Keyword
▷ extends is the keyword used to inherit the properties of a class.
Following is the syntax of extends keyword 21
Syntax for
Inheritance public class My_Calculation extends Calculation {
public void multiplication(int x, int y) {
z = x * y;
class Super System.out.println("The product of the given
{ ..... numbers:"+z);
} }
class Sub extends Super
{ ..... public static void main(String args[]) {
} int a = 20, b = 10;
// derived class object
class Calculation { My_Calculation demo = new My_Calculation();
int z; // base class methods
demo.addition(a, b);
public void addition(int x, int y) { demo.Subtraction(a, b);
z = x + y; // derived class methods
System.out.println("The sum of the given numbers:"+z); demo.multiplication(a, b);
} }
}
public void Subtraction(int x, int y) {
z = x - y;
System.out.println("The difference between the given Output
numbers:"+z);
} The sum of the given numbers:30
} The difference between the given numbers:10
The product of the given numbers:200
22
▷ using the superclass reference
variable ( cal in this case) you
cannot call the method
multiplication(), which belongs to
the subclass My_Calculation.

Calculation demo = new


My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b); // not
possible
▷ A subclass inherits all the members
(fields, methods, and nested
classes) from its superclass.
▷ Constructors are not members, so
they are not inherited by
subclasses, but the constructor of
the superclass can be invoked from
23
the subclass.
The super keyword
The super keyword is similar to this keyword. Following
are the scenarios where the super keyword is used.

▷ It is used to differentiate the members of


superclass from the members of subclass, if they
have same names.

▷ It is used to invoke the superclass constructor from


subclass.

24
Members
class Super_class { // printing the value of variable num
int num = 20; of subclass
// display method of superclass System.out.println("variable ofsub
public void display() { class:"+ sub.num);
System.out.println(“super class display
method"); // printing the value of variable num of
} superclass
} System.out.println("variable of super
class:"+ super.num);
public class Sub_class extends Super_class { }
int num = 10;
// display method of sub class public static void main(String args[]) {
public void display() { Sub_class obj = new Sub_class();
System.out.println(“sub class display method"); obj.my_method();
} }
}
public void my_method() {
// Instantiating subclass Output
Sub_class sub = new Sub_class();
subclass display method
// Invoking the display() method of sub class Superclass display method
sub.display(); variable of sub class:10
variable of super class:20
// Invoking the display() method of superclass 25
super.display();
Invoking Superclass Constructor
▷ If a class is inheriting the
class Superclass {
properties of another class, the
int age;
subclass automatically acquires
the default constructor of the Superclass(int age) {
superclass. this.age = age;
}
▷ For a parameterized
constructor of the superclass, public void getAge() {
the super keyword is in need System.out.println("The value of the variable
named age in super class is: " +age);
}
}
Output public class Subclass extends Superclass {
The value of the variable named age in Subclass(int age) {
super class is: 24 super(age);
}

public static void main(String args[]) {


Subclass s = new Subclass(24);
s.getAge();
}
}
26
The instanceof Keyword
class Animal {
}
▷ Instanceof function
is to ensure
class Mammal extends Animal {
} whether a subclass
class Reptile extends Animal {
is the inherited
} class of a super
public class Dog extends Mammal { class
public static void main(String args[])
{
Animal a = new Animal(); Output
Mammal m = new Mammal();
Dog d = new Dog(); true
System.out.println(m instanceof true
Animal);
System.out.println(d instanceof
Mammal);
true
System.out.println(dinstanceof
Animal); 27
}
Types of Inheritance
▷ There can be three types of inheritance in java:
○ single,
○ multilevel
○ hierarchical.
▷ In java programming, multiple and hybrid
inheritance is supported through interface only.

28
29
Overriding class Animal {
public void move() {
System.out.println("Animals can move");
▷ If a class inherits a method from its }
superclass, then there is a chance to }
override the method provided that it
class Dog extends Animal {
is not marked final. public void move() {
System.out.println("Dogs can walk and run");
}
▷ The benefit of overriding is: ability to }
define a behavior that's specific to
the subclass type, which means a public class TestDog {
subclass can implement a parent
class method based on its public static void main(String args[]) {
Animal a = new Animal(); // Animal reference
requirement. and object
Animal b = new Dog(); // Animal reference but
Dog object
OUTPUT
Animals can move a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class
Dogs can walk and run }
}
30
class Animal {
public void move() {
Example }
System.out.println("Animals can move");

class Dog extends Animal {


TestDog.java:26: error: cannot find public void move() {
symbol System.out.println("Dogs can walk and run");
b.bark(); }
public void bark() {
^ System.out.println("Dogs can bark");
}
symbol: method bark() }
location: variable b of type Animal
public class TestDog {
1 error
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference
This program will throw a compile and object
time error since b's reference type Animal b = new Dog(); // Animal reference but
Animal doesn't have a method by Dog object
the name of bark.
a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class
b.bark();
} 31
Overriding
▷ The argument list should be exactly the same as that of the overridden
method.
▷ The return type should be the same or a subtype of the return type
declared in the original overridden method in the superclass.
▷ The access level cannot be more restrictive than the overridden method's
access level. For example: If the superclass method is declared public then
the overridding method in the sub class cannot be either private or
protected.
▷ Instance methods can be overridden only if they are inherited by the
subclass.
▷ A method declared final cannot be overridden.
▷ A method declared static cannot be overridden but can be re-declared.
▷ If a method cannot be inherited, then it cannot be overridden.
▷ A subclass within the same package as the instance's superclass can
override any superclass method that is not declared private or final.
▷ A subclass in a different package can only override the non-final methods
declared public or protected. 32
Polymorphism
▷ Polymorphism is the ability of an object to take on many forms.
▷ The most common use of polymorphism in OOP occurs when a parent
class reference is used to refer to a child class object.
▷ The reference variable can be reassigned to other objects provided that
it is not declared final.
▷ The type of the reference variable would determine the methods that it
can invoke on the object.
▷ A reference variable can refer to any object of its declared type or any
subtype of its declared type.
▷ A reference variable can be declared as a class or interface type.
public class Animal { }
public class Deer extends Animal { }
Deer d = new Deer();
Animal a = d;
Object o = d;

33
Abstract Classes
▷ Data abstraction is the process of hiding certain
details and showing only essential information to the
user.
▷ Abstraction can be achieved with either abstract
classes or interfaces.
▷ The abstract keyword is a non-access modifier, used
for classes and methods:
▷ Abstract class: is a restricted class that cannot be
used to create objects.
▷ Abstract method: can only be used in an abstract
class, and it does not have a body. The body is
provided by the subclass 34
Example
class Animal
{
void eat(){ Output:
System.out.println("eating...");} barking...
} eating...
class Dog extends Animal
{
void bark(){
System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}

35
Example
class Animal{
void eat(){System.out.println("eating...");}
}
OUTPUT:
class Dog extends Animal{ weeping...
void bark(){System.out.println("barking...");} barking...
}
class BabyDog extends Dog{
eating...
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
36
Hierarchical Inheritance
Example
class Animal{
void eat(){System.out.println("eating...");}
} OUTPUT:
class Dog extends Animal{
void bark(){System.out.println("barking...");}
meowing...
} eating...
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}

37
38
THANKS

39

You might also like