Java——内部类,
分享于 点击 17043 次 点评:38
Java——内部类,
public class Cow {
private double weight;
public Cow(){}
public Cow(double weight)
{
this.weight=weight;
}
private class Cowleg{
private double length;
private String color;
public Cowleg(){}
public Cowleg(double length,String color)
{this.length=length;
this.color=color;}
public void setlength(double length)
{ this.length=length;
}
public double getlength()
{return this.length;
}
public void setcolor(String color){
this.color=color;
}
public String getcolor(){
return this.color;
}
public void info(){
System.out.println("当前牛的颜色"+color+",高"+length);
System.out.println("重"+weight);
}
}
public void test(){
Cowleg c1=new Cowleg(1.12,"黑白相间");
c1.info();
}
public static void main(String[] args) {
Cow cow=new Cow(378.9);
cow.test();
}
}<pre name="code" class="java">public class Dis {
private String prop="外部类的实例变量";
private class Inclass{
private String prop="内部类的实例变量";//private表示只能在外部类内使用
public void info(){
String prop="局部变量";
System.out.println("外部类的实例变量"+Dis.this.prop);//内部类的作用就是可直接访问外部类的私有变量。
System.out.println("内部类的实例变量"+this.prop);
System.out.println("局部变量"+prop);
}
}
public void test(){
Inclass in=new Inclass();
in.info();
}/*非静态内部类的成员只在非静态内部类范围可知,并不能被外部类直接使用。
如果外部类需要访问内部类成员,必须创建非静态内部类对象来访问
所有可以通过函数或者,new Inclass.prop来访问*/
public static void main(String[] args) {
new Dis().test();
}
}
public class Out {
class In{
public In(String msg){
System.out.println(msg);
}
}
}
public class Out {
class In{
public In(String msg){
System.out.println(msg);
}
}
}
public class Fuck {
public static void main(String[] args) {
Out.In a=new Out().new In("hello world");//在外部类以外调用非静态内部类
//如果是静态内部类, Out.In a=new Out().new In(),不需要对象。
}
}
相关文章
- 暂无相关文章
用户点评