Module II Oops

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 49

Module-II

• Inheritance: Inheritance Hierarchies, super keyword – final keyword-


final classes and methods.

• Polymorphism: dynamic binding, method overriding.


• Abstraction-abstract classes and methods.
• The Object class –– Object Cloning – Inner Classes-Garbage
Collection - Finalize Method.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Inheritance
• Inheritance is the process by which one object
acquires the properties and behaviors of another
object.
• Deriving new classes from existing classes such that
the new classes gets all the properties and behaviors
of existing classes is called inheritance
• In java, inheritance can be implemented using
extends keyword
• Use of inheritance is Code Reusability.
• Super Class/Parent Class: Superclass is the class from
where a subclass inherits the properties and
behaviors.
• Sub Class/Child Class: Subclass is a class which
inherits the properties and behaviors of other class.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Inheritance

class A { class TestDemo{


int x=20; public static void main(String[] args) {
void display() B ob=new B();
{ ob.display();
System.out.println("x in super class is="+x); ob.add();
}} }
}
class B extends A {
int y=30;
void add()
{
System.out.println("Addition in sub class is="+(x+y));
}}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Inheritance Hierarchies
1. Single Inheritance
2. Multi-level Inheritance
3. Hierarchical Inheritance

4. Multiple Inheritance

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Single level Inheritance
• A new class is derived from only one super class

Problem:
Create a class Shape has attribute length and readLength() method to read the length.
Create a sub class Rectangle which inherited from Shape class. Rectangle class has
attribute width and readWidth() method to read the width. It also have another method
area() to calculate area of a rectangle. Write a suitable test Java program.
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Single level Inheritance:
class Shape { class TestDemo{
double length; public static void main(String[] args) {
void readLength(double l) Rectangle r=new Rectangle();
{

r.readLength(5);
length=l; r.readWidth(6);
}} r.area();
class Rectangle extends Shape { }
double width; }
void readWidth(double w)
{
width=w;
}
void area()
{
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Multi-level Inheritance
• A new class is derived from already derived class.
class Parent{ class Grandson extends Son {
int p_property=10; int gs_property=30;
void showP() void showGS()
{ {
System.out.println("Parent property System.out.println("Grandson property is="+
is="+p_property); (p_property+s_property+gs_property));
}} }}

class Son extends Parent { class Test{


int s_property=20; public static void main(String[] args) {
void showS() Grandson ob=new Grandson();
{ ob.showP();
System.out.println("Son property is"+ ob.showS();
(p_property+s_property)); ob.showGS();
}} }
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Hierarchical Inheritance
Hierarchical Inheritance: More than one class can be derived from same super class

Problem:
Create a class Shape has attribute length and readLength() method to read the length.
Create a sub class Rectangle which inherited from Shape class. Rectangle class has
attribute width and readWidth() method to read the width. It also have another method
area() to calculate area of a rectangle. Create another subclass Square which inherited
from the Shape class. Square class should have method area() to calculate area of a
square. Write a suitable test Java program.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Hierarchical Inheritance
class Shape { class Square extends Shape {
double length; void area()
void readLength(double l) {
{ System.out.println("Area of Square is="+(length*length));
length=l; }}
}} class Demo{
class Rectangle extends Shape { public static void main(String[] args) {
double width; Rectangle r=new Rectangle();
void readWidth(double w) r.readLength(5);
{ r.readWidth(6);
width=w;
r.area();
}
void area()
Square s=new Square();
{ s.readLength(5);
System.out.println("Area of rectangle is="+(length*width)); s.area();
}} }}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Hierarchical Inheritance

Create a class Vehicle has fields manufacturer’s name, year made, color
and readData() method to read the field values. Create a sub class Car
which is inherited from Vehicle class. Car class has one attribute
number of seats and setData() method to read the number of seats. It
also has another method display () to display the car information.
Create another subclass Bus with one attribute number of seats and
setData() method to read the number of seats. It also has another
method display () to display the Bus information. Write a suitable test
Java program.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Hierarchical Inheritance class Bus extends Vehicle {
import java.util.Scanner;
class Vehicle { int numberOfSeats;
String manufacturer; public void setData() {
int yearMade; Scanner scanner = new Scanner(System.in);
String color; System.out.print("Enter number of seats: ");
void readData() { numberOfSeats = scanner.nextInt();
Scanner scanner = new Scanner(System.in); }
System.out.print("Enter manufacturer's name: void display() {
"); System.out.println("\nBus Information:");
manufacturer = scanner.nextLine(); System.out.println("Manufacturer: " + manufacturer);
System.out.print("Enter color: "); System.out.println("Year Made: " + yearMade);
color = scanner.nextLine(); System.out.println("Color: " + color);
System.out.print("Enter year made: "); System.out.println("Number of Seats: " + numberOfSeats);
yearMade = scanner.nextInt(); }}
}
} class Main {
class Car extends Vehicle { public static void main(String[] args) {
int numberOfSeats; // Test Car class
public void setData() { Car car = new Car();
Scanner scanner = new Scanner(System.in); System.out.println("Enter car details:");
System.out.print("Enter number of seats: "); car.readData();
numberOfSeats = scanner.nextInt(); car.setData();
} car.display();
void display() {
System.out.println("\nCar Information:"); // Test Bus class
System.out.println("Manufacturer: " + manufacturer); Bus bus = new Bus();
System.out.println("Year Made: " + yearMade); System.out.println("\nEnter bus details:");
System.out.println("Color: " + color); bus.readData();
System.out.println("Number of Seats: " + numberOfSeats); bus.setData();
} } bus.display();
}
}
Multiple Inheritance
Multiple Inheritance:
• Multiple Inheritance is a feature of an object-oriented concept, where a class can
inherit properties of more than one parent class.
• Java doesn’t support Multiple Inheritance directly but using interfaces we can
implement this.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


access control / Member Access and Inheritance
• Java’s access specifiers are public, private, and protected. Java also defines a default
access level.
• protected applies only when inheritance is involved.
• When a member of a class is specified as public, then that member can be accessed by
any other code.
• When a member of a class is specified as private, then that member can only be
accessed by other members of its class.
• Although a subclass includes all of the members of its superclass, it cannot access those
members of the superclass that have been declared as private.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


access control / Member Access and Inheritance

class A { class Access {


int i; // public by default public static void main(String args[]) {
private int j; // private to A B ob = new B();
void readData(int x, int y) { ob.readData(10, 12);
i = x; ob.sum();
j = y; System.out.println("Total is " +ob.total);
} }
} }
// A's j is not accessible here.
class B extends A {
int total;
void sum() {
total = i + j; / /ERROR, j is not accessible here
}}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
super keyword

• The super keyword is used to refer immediate super class object.


Uses:
1. super can be used to refer super class instance variables and methods.
super.variablename;
super.methodname();
2. super() can be used to invoke super class constructor.
super(val1,val2…);

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


super keyword

class A {
int x=20; class SuperEx{
void show() public static void main(String[] args) {
{ B ob=new B();
System.out.println("x in super class is="+x); ob.show();
} }
} }
class B extends A {
int x=30;
void show()
{
System.out.println("x in sub class is="+x);
System.out.println("x in super class is="+super.x);
super.show();
}}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
super keyword
class Shape {
double length,width;
Shape(double l,double w) class SuperEx2{
{ public static void main(String[] args) {
length=l; Rectangle r=new Rectangle();
width=w; r.area();
}} }
class Rectangle extends Shape { }
Rectangle()
{
super(5,6);
}
void area()
{
System.out.println("Area of Rectangle is="+(length*width));
}}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Polymorphism
Polymorphism
• Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface
to be used for a general class of actions.
• The same entity (method or operator or object) can perform different operations in
different scenarios.
• A person at the same time can have different characteristics. Like a man at the same time
is a father, a husband, an employee. So the same person possesses different behavior in
different situations. This is called polymorphism.

• In Java polymorphism is mainly divided into two types:


1. Compile-time Polymorphism
2. Runtime Polymorphism

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Compile-time Polymorphism
• Compile-time polymorphism is achieved by method
overloading.
Method Overloading:
• Method overloading in java is a feature that allows a class
to have more than one method with the same name, but
with different parameters.
• Java supports method overloading through two
mechanisms:
1.By changing the number of parameters
2.By changing the data type of parameters

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Method Overloading
class Calculator {
class Main {
void add(int a, int b) { public static void main(String[] args) {
System.out.println(a + b); Calculator calc = new Calculator();
} calc.add(5, 10);
void add(int a, int b, int c) { calc.add(5, 10, 15);
System.out.println(a + b + c); calc.add(2.5, 3.5);
} calc.add("Hello, ", "world!");
void add(double a, double b) { }
System.out.println(a + b); }
} Output:
void add(String str1, String str2) { 15
System.out.println(str1 + str2); 30
6.0
} Hello, world!
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Method Overloading
Create a class named Billing that includes two overloaded computeBill() methods
for a photo book store. When computeBill() receives a single parameter, it
represents the price of one photo book ordered. Add 8% tax, and return the total
due. When computeBill() receives three parameters, they represent the price of a
photo book, the quantity ordered, and a coupon value. Multiply the quantity and
price, reduce the result by the coupon value, and then add 8% tax and return the
total due. Write a main() method that tests all two overloaded methods

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Method Overloading
class Billing {
double computeBill(double p){ class Demo2{
double total=p+(p*0.08); public static void main(String[] args)
return total; {
} Billing ob=new Billing();
double total;
double computeBill(double p,int n,double c) total=ob.computeBill(20);
{
System.out.println(total);
double total=(n*p-c)+((n*p-c)*0.08);
return total;
} total=ob.computeBill(20,5,10);
}
System.out.println(total);
}
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Run-time Polymorphism

• This type of polymorphism is achieved by Method


Overriding.
Method Overriding:
• In Java, method overriding occurs when a subclass has the
method with same name and signature as the method in
super class.
• It is also known as Dynamic Method Dispatch.
• It is a process in which a method call to the overridden
method is resolved at Runtime.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Method Overriding
class Animal {
public void makeSound() {
System.out.println("Animal class Main {
makes a sound"); public static void main(String[] args) {
} Dog d = new Dog();
} Cat c = new Cat();

class Dog extends Animal { d.makeSound();


public void makeSound() { c.makeSound();
System.out.println("Dog }}
barks");
}
}

class Cat extends Animal {


public void makeSound() {
System.out.println("Cat
meows");
}
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Method Overriding
Create a class 'Degree' having a method 'getDegree' that retuns "I got a degree". It
has two subclasses namely 'Undergraduate' and 'Postgraduate' each having a method
with the same name that returns "I am an Undergraduate" and "I am a Postgraduate"
respectively. Call the method by creating an object of each of the three classes.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Method Overriding

class Degree { class Postgraduate extends Degree {


String getDegree() String getDegree()
{ {
String message="I got a degree"; String message="I am a Postgraduate";
return message; return message;
} }
} }
class Undergraduate extends Degree { class Demo4{
String getDegree() public static void main(String[] args)
{ {
String message="I am an Undergraduate"; Undergraduate ob1= new Undergraduate();
return message; Postgraduate ob2= new Postgraduate();
} System.out.println(ob1.getDegree());
}
System.out.println(ob2.getDegree());
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE }}
Method Overriding

A boy has his money deposited $1000, $1500 and $2000 in banks-Bank A,
Bank B and Bank C respectively. We have to print the money deposited by
him in a particular bank.
Create a class 'Bank' with a method 'getBalance()' which returns 0. Make
its three subclasses named 'BankA', 'BankB' and 'BankC' with a method
with the same name 'getBalance()' which returns the amount deposited in
that particular bank. Call the overridden method 'getBalance()' by the
object of each of the three banks.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Method Overriding
class BankC extends Bank {
class Bank { int getBalance() {
int getBalance() { return 2000; // Amount deposited in Bank C
return 0; // Default implementation returns 0
}
}
}
}
class BankA extends Bank {
public class Main {

int getBalance() { public static void main(String[] args) {


return 1000; // Amount deposited in Bank A BankA bankA = new BankA();
} BankB bankB = new BankB();
} BankC bankC = new BankC();
class BankB extends Bank {
System.out.println("Amount deposited in Bank A: $" + bankA.getBalance());
int getBalance() {
System.out.println("Amount deposited in Bank B: $" + bankB.getBalance());
return 1500; // Amount deposited in Bank B
}
System.out.println("Amount deposited in Bank C: $" + bankC.getBalance());

} }
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
final keyword

• final keyword is used to modifies the accessibility of a variable, method and class.

Final variables: When a variable is declared as final, its value cannot be changed once it has
been initialized.
Ex: final double pi=3.14;
Final methods: When a method is declared as final, it cannot be overridden by a subclass.
Final classes: When a class is declared as final, it cannot be extended by a subclass.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


final keyword

To Prevent method overriding: To Prevent Inheritance:

class A { final class A {


final void show() { void show() {
System.out.println("It is super class System.out.println("It is super class method");
method"); }}
}} class B extends A {
class B extends A { void show() {
void show() { System.out.println("It is sub class method");
System.out.println("It is sub class method"); }}
}} class final_class{
class final_method{ public static void main(String args[]) {
public static void main(String args[]) { B ob = new B();
B ob = new B(); ob.show();
ob.show(); }
}} }
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Access Specifiers

• An access specifier specifies how to access-the


members of a class or a Class itself.
private: 'private' members of a-class are not
accessible any where outside the class.
public: 'public' members of a class are accessible
every where outside the class.
protected: 'protected' allow members to be seen
outside current package, but only to classes that
subclass your class directly
default: 'default' members are accessible outside
the class, but within the same directory.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Access Specifiers

class Access{ class AccessDemo {


private int a; public static void main(String args[]) {
public int b; Access ob=new Access();
protected int c; ob.a=10; // error a has private access in Access
int d; ob.b=20;
void add() ob.c=30;
{ ob.d=40;
System.out.println(a+b+c+d); ob.add();
} }
} }

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


abstract class

• A concrete method is a method with implementation.


• An abstract method is a method without implementation(body).
Ex: abstract double area();
• An abstract class is a class that contains zero or more abstract methods.
• Both the abstract class and the abstract methods should be declared by using keyword
abstract.
• An abstract class can have abstract methods as well as concrete methods.
• Any class that contains one or more abstract methods must be declared as abstract class.
Syntax:
public abstract class ClassName
{
public abstract methodName();
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
abstract class

• An abstract class does not allow you to create objects of its type.
• The child classes which inherit the abstract class must provide the implementation of
these inherited abstract methods.
• If abstract methods are not implemented in its sub classes then you should declare those
sub class as abstract.
• An abstract class can have parameterized constructors.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


abstract class
Create an abstract class 'Animals' with one abstract method ‘makeSound()’. Now create a class
'Cats' with a method ' makeSound ' which prints "Cats meow" and a class 'Dogs' with a method
'makeSound' which prints "Dogs bark", both inheriting the class 'Animals'. Now create an object
for each of the subclasses and call their respective methods.

abstract class Animals{ class Dogs extends Animals{


abstract void makeSound(); void makeSound() {
} System.out.println("Dogs bark");
}}
class Cats extends Animals{ class Animalsdemo {
void makeSound() { public static void main(String[] args)
System.out.println("Cats meow"); {
} Cats c = new Cats();
} Dogs d = new Dogs();
c.makeSound();
d.makeSound();
}}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
abstract class

We have to calculate the area of a rectangle, and a triangle. Create an abstract class
'Shape' with two fields dim1 and dim2 and abstract method area(). Include a constructor to
initialize dim1 and dim2. Create two child classes of Shape: Rectangle and Triangle. The
constructor of both the sub classes takes dim1 and dim2 values as its parameters. Create
an object for each of the two classes and print the area.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


abstract class
abstract class Shape {
double dim1,dim2; class Triangle extends Shape {
abstract void area(); Triangle(double l,double w)
Shape(double d1,double d2) {
{ super(l,w);
dim1=d1; }
dim2=d2; void area()
}} {
class Rectangle extends Shape { System.out.println("Area of Triangle is="+
Rectangle(double l, double w) (dim1*dim2*0.5));
{ }}
super(l,w); class Demo{
} public static void main(String[] args) {
void area() Rectangle r=new Rectangle(5,6);
{ r.area();
System.out.println("Area of Rectangle is="+ Triangle s=new Triangle(7,8);
(dim1*dim2)); s.area();
}} }}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
abstract class

Create an abstract class named Book. Include a String field for the book’s title and a double
field for the book’s price. Within the class, include a constructor that requires the book title,
and add two get methods—one that returns the title and one that returns the price. Include
an abstract method named setPrice(). Create two child classes of Book: Fiction and
NonFiction. Each must include a setPrice() method that sets the price for all Fiction Books
to $24.99 and for all NonFiction Books to $37.99. Write a constructor for each subclass,
and include a call to setPrice() within each. Write a class demonstrating that you can create
both a Fiction and a NonFiction Book, and display their fields.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


abstract class
abstract class Book {
class Fiction extends Book { class Demo2{
String btitle;
Fiction(String s) public static void main(String[] args) {
double bprice;
{ Fiction f=new Fiction("Beloved");
Book(String s)
super(s); f.setPrice(24.99);
{
} System.out.println("Fiction book
btitle=s;
void setPrice(double p){ title:"+f.getTitle());
}
bprice=p; System.out.println("Fiction book
String getTitle()
} Price:"+f.getPrice());
{
} NonFiction nf=new NonFiction("Sapiens");
return btitle;
class NonFiction extends Book { nf.setPrice(37.99);
}
NonFiction(String s) System.out.println("NonFiction book
double getPrice()
{ title:"+nf.getTitle());
{
super(s); System.out.println("NonFiction book
return bprice;
} Price:"+nf.getPrice());
}
void setPrice(double p){ }}
abstract void setPrice(double p);
}} bprice=p;
}}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Garbage Collection - Finalize Method

• In java, garbage means unreferenced objects.


• Garbage Collection is process of reclaiming unused memory automatically.
• In other words, it is a way to destroy the unused objects.
• Garbage collection is performed by a daemon thread called Garbage Collector(GC).
• This thread calls the finalize() method before object is garbage collected.

How can an object be unreferenced?:


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

Employee e1=new Employee();


Employee e2=new Employee();
e1=e2; // By assigning a reference to another

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Garbage Collection - Finalize Method

gc() method:
• The gc() method is used to invoke the garbage collector to perform cleanup processing.
The gc() is found in System class.

public static void gc(){}

finalize() method:
• The finalize() method is invoked each time before the object is garbage collected.
• This method can be used to perform cleanup processing.
• This method is defined in Object class
protected void finalize(){}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Garbage Collection - Finalize Method

public class TestGarbage1{


public void finalize(){
System.out.println("object is garbage collected");
}

public static void main(String args[]){


TestGarbage1 ob=new TestGarbage1();

ob=null;
System.gc();
}
}
O/P:
object is garbage collected
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
The Object class

• The Object class is the parent class of all the classes in java by default.
• All other classes are subclasses of Object. That is, Object is a superclass of all other
classes.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Object Cloning

• 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.

protected Object clone() throws CloneNotSupportedException

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Object Cloning

class Student implements Cloneable{ class demo {


int rollno; public static void main(String args[]){
String name; try{
Student(int rollno,String name){ Student s1=new Student(1,"Devansh");
this.rollno=rollno; Student s2=(Student)s1.clone();
this.name=name;
} System.out.println(s1.rollno+" "+s1.name);
public Object clone()throws System.out.println(s2.rollno+" "+s2.name);
CloneNotSupportedException{ }catch(CloneNotSupportedException c){}
return super.clone(); }}
} O/P:
} 1 Devansh
1 Devansh

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Inner classes
• In Java, it is also possible to nest classes (a class within a class).
• To access the inner class, create an object of the outer class, and then create an object of
the inner class
Syntax:
Outerclass{
….
Innerclass{
….
}
}
Object creation:
Outerclass Outer=new Outerclass();
Outerclass.Innerclass In=Outer.new InnerClass();

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Inner classes

class Outer{
int x = 10; public class Main {
public static void main(String[] args) {
class Inner { Outer Out= new Outer();
int y = 5; Outer. Inner In = Out. new Inner();
void add() In.add();
{
System.out.println(x+y); }
} }
}
}
O/P: 15

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Inner classes
Private Inner Class
• Unlike a "regular" class, an inner class can be private or protected. If you don't want
outside objects to access the inner class, declare the class as private:

class Outer{
public class Demo {
int x = 10;
public static void main(String[] args) {
Outer Out= new Outer();
private class Inner {
Outer. Inner In = Out. new Inner();
int y = 5;
In.add();
void add()
{
}
System.out.println(x+y);
}
}
} Error: Outer.Inner has private access in Outer
} Outer.Inner In = Out.new Inner();

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Inner classes
Static Inner Class
• An inner class can also be static, which means that you can access it without creating
an object of the outer class

class Outer{ public class Main {


int x = 10; public static void main(String[] args) {
Outer.Inner In = new Outer.Inner();
static class Inner { System.out.println(In.y);
int y = 5;
} }
} }

O/P: 5

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE

You might also like