public class Show0 {
/**
* 把一个类定义在另一个类的内部,就是内部类。
*
*
*/
private int id=123;
private String name="hero";
public showInner0 createInner0(){
return new showInner0();
}
class showInner0{
int stuId=id;
String name="tom";
public void say(){
System.out.println(name);
}
}
class showInner1{
}
public static void main(String[] args) {
Show0 s=new Show0();
Show0.showInner0 inner0=s.createInner0();
inner0.say();
}
}
package com.hero.show;
/**
* 创建内部类对象,内部类引用外部类
* @author hero
*
*/
public class Show1 {
public class Inner{
public Show1 outer(){
return Show1.this;
}
}
}
class hero1{
Show1 show1=new Show1();
Show1.Inner inner=show1.new Inner();
}
package com.hero.show;
/**
* 内部类与向上转型
* @author hero
* 内部类向上转型成父类,尤其是转型成接口的时候
*/
public class Show2 {
private class BMW implements Car{
}
protected class OFO implements Bike{
}
public Car CarFactory(){
return new BMW();
}
public Bike BikeFactory(){
return new OFO();
}
}
package com.hero.show;
/**
* 在方法和作用域内的的内部类
* @author hero
*
*/
public class Show3 {
public Car CarFactory(){
class BMW implements Car{
}
return new BMW();
}
public Car test(){
if(true){
class BMW implements Car{
}
return new BMW();
}
return null;
}
}
package com.hero.show;
/**
* 匿名内部类
* @author hero
*
*/
public class Show4 {
public Car shopping(final String name){
return new Car() {
private String love=name;
};
}
}
package com.hero.show;
import com.hero.show.Show5.hungry;
/**
* 嵌套类,如果不需要内部类和外部类有联系,将内部类声明为static
* 普通的内部类对象隐式的保存了一个引用,指向创建他的外围类对象。
* 但是static就不是,嵌套类意味着:
* 1.创建嵌套类对象,不需要外围类对象
* 2.不能从嵌套类的对象中访问非静态的外围类对象
* 普通的内部类不可以有static字段,也不能包含嵌套类,但是嵌套类可以有
* @author hero
*
*/
public class Show5 {
public static class hungry{
}
}
class dinner{
hungry h=new hungry();
}