javainnerclass.pdf

(173 KB) Pobierz
623021259 UNPDF
Java Inner Class
1
623021259.003.png 623021259.004.png
What is an Inner Class?
Class declared within another class
Accessing the members of the inner class:
Need to instatiate an object instance of an inner class
first
Example:
innerObj.innerMember = 5;
//innerObj is an instance of the inner class
//innerMember is a member of the inner class
2
623021259.005.png
Accessing Members of Outer class
within an Inner class
Methods of the inner class can directly access
members of the outer class
Example:
1 class Out {
2 int OutData;
3 class In {
4 void inMeth() {
5 OutData = 10;
6 }
7 }
8 }
3
623021259.006.png
Java Program Structure: Inner
Classes
1 class OuterClass {
2 int data = 5;
3 class InnerClass {
4 int data2 = 10;
5 void method() {
6 System.out.println(data);
7 System.out.println(data2);
8 }
9 }
10
11 //continued...
4
623021259.001.png
Java Program Structure:
9 public static void main(String args[]) {
10 OuterClass oc = new OuterClass();
11 InnerClass ic = oc.new InnerClass();
12 System.out.println(oc.data);
13 System.out.println( ic.data2 );
14 ic.method();
15 }
16 }
5
623021259.002.png
Zgłoś jeśli naruszono regulamin