Java : OuterClass in Java
A PPT PRESENTATION FOR
JAVA PROGRMING
2.
Outer Class
An outerclass in Java is a class that is not defined inside any other class. It is the
top-level
class that can contain fields, methods, constructors, nested classes, and inner
classes.
Every Java program starts with at least one outer class.
Key points:
- Defined at the top level, outside of other classes.
- - Can be public or package-private.
- - Contains main() method in most programs.
- - Can include inner classes, but itself is the main container.
3.
Basic Outer ClassExample
public class Car {
String brand;
int year;
Car(String brand, int year) {
this.brand = brand;
this.year = year;
}
void display() {
System.out.println("Brand: " + brand + ", Year: " + year);
}
public static void main(String[] args) {
Car c = new Car("Toyota", 2022);
c.display();
}
}
Example of a simple outer class with fields and methods
4.
Outer Class withInner Class
public class University {
String name = "ABC University";
class Department { String deptName;
Department(String deptName) {
this.deptName = deptName;
}
void show() {
System.out.println(name + " - Department: " + deptName);
}
}
public static void main(String[] args) {
University u = new University();
University.Department d = u.new Department("Computer Science");
d.show();
}
}
An outer class can contain an inner class. The inner class can access members of the outer
class :
5.
Outer Class withStatic Nested Class
A static nested class is defined inside an outer class but declared static. It does not
require an instance of the outer class to be created.
public class Library {
// Static nested class
static class Book {
String title;
Book(String title) { this.title = title; }
void showTitle() {
System.out.println("Book: " + title);
}
}
public static void main(String[] args) {
Library.Book b = new Library.Book("Java Programming");
b.showTitle();
}
}
6.
MENTORSHIP:- PROF. SWETAKUMARI
NAME : sushant gaurav
BRANCH : CSE
SEMESTER : 5th
ROLL NO. : 2023-CSE-53
INSTITUTE : GOVERNMENT POLYTECHNIC MUZFFARPUR
PRESENTED BY :-