java学习(2)
Java支持在一个类中声明看另一个类,这样的类称左内部类。
1.内部类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class China { 2 final String song="义勇军进行曲"; 3 private Beijing beijing; 4 China(){ 5 beijing=new Beijing(); 6 } 7 //Beijing beijing=new Beijing(); 8 public Beijing getBeijing(){ 9 return beijing; 10 } 11 String getSong(){ 12 return song; 13 } 14 class Beijing{ //内部类的声明 15 String name="北京"; 16 void speak(){ 17 System.out.println("我们是"+name+"\n我们的国歌是:"+getSong()); 18 } 19 } 20 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Example6_1 { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 China china= new China(); 8 china.getBeijing().speak(); 9 10 } 11 12 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
我们是北京
我们的国歌是:义勇军进行曲
2.匿名类:Java允许直接使用一个类的子类的类体创建一个子类的对象,也就是说,创建子类对象的时候,除了使用父类的构造方法外还有类体,此类体被认为是一个子类去掉声明后的类体,称作“匿名类”。
2.1和类有关的匿名类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 abstract class J_Class{ 2 int m_data; 3 4 public J_Class(int i){ 5 m_data=i; 6 } 7 8 public abstract void mb_method(); 9 } 10 11 public class Example6_2 { 12 13 /** 14 * @param args 15 */ 16 public static void main(String[] args) { 17 J_Class b=new J_Class(5){ 18 public void mb_method(){ 19 System.out.println("m_data="+m_data); 20 } 21 }; //父类型为类J_Class的匿名内部类结束 22 b.mb_method(); 23 } 24 25 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 abstract class Speak{ 2 public abstract void speakHello(); 3 } 4 5 class Student{ 6 void f(Speak sp){ 7 sp.speakHello(); 8 } 9 } 10 11 public class Example6_3 { 12 13 /** 14 * @param args 15 */ 16 public static void main(String[] args) { 17 Speak speak=new Speak(){ //匿名内部类 18 public void speakHello(){ 19 System.out.println("大家好,祝工作顺利!"); 20 } 21 }; 22 speak.speakHello(); 23 Student st=new Student(); 24 st.f(new Speak(){ //匿名内部类 25 public void speakHello(){ 26 System.out.println("I am a student,how are you?"); 27 } 28 }); 29 } 30 31 }
2.2和接口有关的匿名类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //与接口有关的匿名类 2 interface Cubic{ 3 double getCubic(double x); 4 } 5 6 class A{ 7 void f(Cubic cubic){ 8 double result=cubic.getCubic(3); 9 System.out.println("result="+result); 10 } 11 } 12 13 public class Example6_4 { 14 15 /** 16 * @param args 17 */ 18 public static void main(String[] args) { 19 Cubic cu= new Cubic(){ //匿名类的声明 20 public double getCubic(double x){ 21 return x*x*x; 22 } 23 }; 24 double m=cu.getCubic(5); 25 System.out.println("m="+m); 26 A a=new A(); 27 a.f(new Cubic(){ //实现接口的匿名类的类体 28 public double getCubic(double x){ 29 return x*x*x; 30 } 31 }); 32 } 33 34 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
m=125.0
result=27.0