Skip to content

Commit

Permalink
静态与非静态内部类Java、Kotlin对比实现
Browse files Browse the repository at this point in the history
  • Loading branch information
BetterZhang committed Jun 28, 2017
1 parent ef810db commit 6a58dd0
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/com/betterzhang/learnkotlin/java/Outer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.betterzhang.learnkotlin.java;

/**
* Created by IntelliJ IDEA.
* Author : Andrew Zhang
* Email : betterzhang.dev@gmail.com
* Time : 2017/06/28 上午 10:42
* Desc : 静态与非静态内部类
*/
public final class Outer {

private int bar = 100;

public static class Nested {
public final String foo() {
return "Hello Java";
}
}

public final class Inner {
public final int foo() {
return bar; // 可以访问外部类成员
}
}

public static void main(String[] args) {
System.out.println(new Outer.Nested().foo());
System.out.println(new Nested().foo());
// System.out.println(new Outer().Inner().foo()); // 不能在其他类中实例化非静态内部类
}

}
31 changes: 31 additions & 0 deletions src/com/betterzhang/learnkotlin/kotlin/Outer.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.betterzhang.learnkotlin.kotlin

/**
* Created by IntelliJ IDEA.
* Author : Andrew Zhang
* Email : betterzhang.dev@gmail.com
* Time : 2017/06/28 上午 10:50
* Desc : description
*/
class Outer {

private var bar: Int = 100

// 嵌套类
class Nested {
// 不能访问外部类成员
fun foo() = "Hello Kotlin"
}

// 内部类
inner class Inner {
// 可以访问外部类成员
fun foo() = bar
}

}

fun main(args: Array<String>) {
println(Outer.Nested().foo())
println(Outer().Inner().foo())
}

0 comments on commit 6a58dd0

Please sign in to comment.