think in java 笔记

刚开始的时候,想测试下 假如class A  和classB , B extends A ,那么当A test = new B();的时候 test.方法 调用的是父类方法还是子类方法,测试下


public class SubClassTest {

private static A forTest = new B();

public static void main(String args){

forTest.print();

}

private  class A {public void print(){

System.out.println("this is a method of A!");

}

}

private  class B extends A{

@Overridepublic void print(){

System.out.println("this is a method of B!");

}

}

}

但是编译报错

No enclosing instance of type Foo is accessible. Must qualify the allocation with an enclosing instance of type Foo (e.g. x.new A() where x is an instance of Foo).

就是说未实例化的对象不能实例化其内部类。其实可以这么理解,就是相当于一个类在没有对象的时候,你不能给它的非静态成员赋值。大概可以这么理解吧

把两个内部类改成static 该问题解决,但是又出现新问题了,selection doesnot have a main type,后来发现main方法的参数是有问题的

应该是public void main(String [] args){


}

显示的结果是 this is a method from B...确实和我预想的不太一样..这应该就是所谓的动态绑定....




二、 所有成员变量都会被自动初始化

主类型 默认值

Boolean false
Char '\u0000'(null)
byte (byte)0
short (short)0
int 0
long 0L
float 0.0f
double 0.0d

在java中,通过方法传递对象,都是传递对象的句柄,除了那些主类型,int boolen ,long 等等

static 静态方法不能调用非静态方法,因为非静态方法需要把其调用的对象也作为参数传给方法 ,但是static静态方法是没有对象的。

逻辑运算符&&    A&&B 这个时候,如果A为flase 那么B 就不会被执行

例如   (1==2)&&(i++<5) 这个时候 i的值就不会被改变。




三、初始化

构造器里面可以调用构造器,并且只能调用一个构造器,而且必须是我们所做的第一件事,其他方法不能调用构造器




public class A {
A(String a){
System.out.println("A's constructor! "+a);
}


}




public class SubClassTest {


public static void main(String[] args){


}
static{
System.out.println("static block 1");
}

A mA = new A("IS NOT a static variable!");
static{
System.out.println("static block 2");
}

static A a = new A("static variable!");


static{
System.out.println("static block 3");
}






}


运算结果

static block 1
static block 2
A's constructor! static variable!
static block 3

可见 在一个类先运行的是static块和static成员变量,其具有相同的优先级,并且按照顺序运行。比这个类的构造方法还要早。非静态成员变量只有在该类被实例化的时候才会被初始化。



如果上述写错了 希望积极指出 谢谢


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值