use*_*045 6 java object instance
System.out.print("Enter Room Number: ");
int a4 = scan.nextInt();
scan.nextLine();
booking[count]= new RoomBooking (a1,a2,a3,a4);
count++;
if (/* if the object is an instance of RoomBooking(subclass) */) {
for (int y = 0; y < count; y++) {
if (a4 == (((RoomBooking) booking[y]).getRoomNumber())) {
System.out.print("Used number, Please Try again");
}
}
}
Run Code Online (Sandbox Code Playgroud)
"如果对象是RoomBooking(子类)的一个实例"我怎么能在java中编写它?
对不起,如果没有意义,还在学习.
如果你需要知道发生了什么,有2个班级.预订(正常预订)和RoomBooking(延伸预订)..由于我们必须创建一个存储两者混合的数组,我需要检查对象(a4)是否是RoomBooking的实例,所以我可以比较数字.
我试过if((RoomBooking.class.isInstance(a4))){...}但它没有用.
还有isAssignableFrom方法Class.
if(CabinBooking.class.isAssignableFrom(object.getClass())
Run Code Online (Sandbox Code Playgroud)
我更喜欢@assylias建议的方法,因为它甚至可以工作,object == null而isAssignableFrom如果参数为null则会抛出错误.因此,您必须检查实例是否为空.
if(object instanceof CabinBooking.class)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27833 次 |
| 最近记录: |