2
2
//To access the inner class, create an object of the outer class, and then
//create an object of the inner class:
class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
}
}
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 OuterClass {
int x = 10;
An inner class can also be static, which means that you can access it without
creating an object of the outer class:
class OuterClass {
int x = 10;
// Outputs 5
One advantage of inner classes, is that they can access attributes and methods of
the outer class:
class OuterClass {
int x = 10;
class InnerClass {
public int myInnerMethod() {
return x;
}
}
}
In Java, it is possible to inherit attributes and methods from one class to another.
We group the "inheritance concept" into two categories:
In the example below, the Car class (subclass) inherits the attributes and methods
from the Vehicle class (superclass):
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the
value of the modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}