如何在Java中访问内部类?
在Java中,内部类是指在主要引入的类或接口内部声明的类,总结起来,与Java相同的逻辑相关类是纯面向对象的,因此更接近现实世界。建议对内部类有足够的了解,先创建外部类的对象,再创建内部类的对象。由于内部类存在于外部类中,我们必须实例化外部类才能实例化内部类。因此,要访问内部类,首先创建外部类的对象,然后再创建内部类的对象。
所以我们知道Java中有多种类型的内部类
示例 1:
Java
// Java Program to demonstrate How to Access Inner Class
// Importing required classes
import java.io.*;
// Class 1
// Outer class
class Outer {
// Class 2
// Inner class
class Inner {
// Data member defined inside inner class
int num = 10;
}
}
// Class 2
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an instance of outer class inside main()
Outer obj1 = new Outer();
// Creating an instance of inner class inside main()
Outer.Inner obj2 = obj1.new Inner();
// Accessing inner class's data member
System.out.println(obj2.num);
}
}
Java
// Java Program to Demonstrate Private Inner Class
// Importing required classes
import java.io.*;
// Class 1
// Outer class
class Outer {
// Private inner class
private class Inner {
int num = 10;
}
}
// Class 2
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Outer class object
Outer obj1 = new Outer();
// Inner class object
Outer.Inner obj2 = obj1.new Inner();
// Accessing inner class's data member
System.out.println(obj2.num);
}
}
Java
// Java Program to Demonstrate Static Inner Class
// Importing required classes
import java.io.*;
// Class 1
// Outer class
class Outer {
// Static inner class
static class Inner {
// Inner class member variable
int num = 10;
}
}
// Class 2
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Inner class object
Outer.Inner obj2 = new Outer.Inner();
// Accessing inner class's data member
System.out.println(obj2.num);
}
}
输出
10
现在让我们提出另一个演示私有内部类的示例。因为内部类可以设为私有 或者 protected ,与“常规课程”不同。如果内部类是私有的,则不可能使用外部对象访问该类。
示例 2:
Java
// Java Program to Demonstrate Private Inner Class
// Importing required classes
import java.io.*;
// Class 1
// Outer class
class Outer {
// Private inner class
private class Inner {
int num = 10;
}
}
// Class 2
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Outer class object
Outer obj1 = new Outer();
// Inner class object
Outer.Inner obj2 = obj1.new Inner();
// Accessing inner class's data member
System.out.println(obj2.num);
}
}
输出:
现在让我们提出另一个说明静态内部类的示例。据我们所知 这 内部类可以是静态的。我们可以在不创建外部类的对象的情况下访问静态内部类。
示例 3:
Java
// Java Program to Demonstrate Static Inner Class
// Importing required classes
import java.io.*;
// Class 1
// Outer class
class Outer {
// Static inner class
static class Inner {
// Inner class member variable
int num = 10;
}
}
// Class 2
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Inner class object
Outer.Inner obj2 = new Outer.Inner();
// Accessing inner class's data member
System.out.println(obj2.num);
}
}
输出
10