Java学习笔记-类的创建与引用-18.08.02
今天学习的内容是类的创建与引用:
- 使用class创建新类
- 在新类中可以使用this来指代新类
- instanceof 用于判断某个对象是否属于某个指定的类或其子类的实例
例程代码
例程代码如下:
public class instance {
public static void main(String args[]){
OtherClass Inst= new OtherClass();
if(Inst instanceof OtherClass)
{
System.out.println("是");
Inst.nMember=100;
int nMember=Inst.nMember;
System.out.print(nMember);
}
}
class OtherClass{
public int nMember;
OtherClass(){}
OtherClass(int nMember){
this.nMember=nMember;
}
}
}
此例程变异过程中存在问题:在main中声明新类Inst会报错:
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
No enclosing instance of type instance is accessible. Must qualify the allocation with an enclosing instance of type instance (e.g. x.new A() where x is an instance of instance).
原因是,在Java中:
(1)类的静态方法不能直接调用动态方法。
(2)类的静态方法不能初始化内部类(包括该类的内部类,和其他文件中的内部类)。
(3)类的静态方法可以初始化其他类文件中的类。
(4)类的静态方法可以初始化静态类(包括静态内部类)。
因此,可以将OtherClass声明为静态类。
修正后的代码
按照上述思路修正后的代码如下:
public class instance {
public static void main(String args[]){
OtherClass Inst= new OtherClass();
if(Inst instanceof OtherClass)
{
System.out.println("是");
Inst.nMember=100;
int nMember=Inst.nMember;
System.out.print(nMember);
}
}
public static class OtherClass{
public int nMember;
OtherClass(){}
OtherClass(int nMember){
this.nMember=nMember;
}
}
}
编译通过执行后输出以下结果:
是
100
值得注意的便是在静态方法中不能够直接调用动态方法,因此在创建内部方法的时候如果考虑到需要在静态方法中调用时,可以将其创建为静态方法。由于本人刚入门学习Java编程与使用,在本文中如果出现错误,希望读者提出指正意见。