访问修饰符(access modifier)
1) public(公共的):被public所修饰的属性和方法可以被所有类访问。
2) protected(受保护的):被protected所修饰的属性和方法可以在类内部、相同包以及该类的子类所访问。
3) private(私有的):被private所修饰的属性和方法只能在该类内部使用
4) 默认的(不加任何访问修饰符):在类内部以及相同包下面的类所使用。
instanceof运算符
The instanceof
operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
The following program, InstanceofDemo
, defines a parent class (named Parent
), a simple interface (named MyInterface
), and a child class (named Child
) that inherits from the parent and implements the interface.
class InstanceofDemo {
public static void main(String[] args) {
Parent obj1 = new Parent();
Parent obj2 = new Child();
System.out.println("obj1 instanceof Parent: "
+ (obj1 instanceof Parent));
System.out.println("obj1 instanceof Child: "
+ (obj1 instanceof Child));
System.out.println("obj1 instanceof MyInterface: "
+ (obj1 instanceof MyInterface));
System.out.println("obj2 instanceof Parent: "
+ (obj2 instanceof Parent));
System.out.println("obj2 instanceof Child: "
+ (obj2 instanceof Child));
System.out.println("obj2 instanceof MyInterface: "
+ (obj2 instanceof MyInterface));
}
}
class Parent {}
class Child extends Parent implements MyInterface {}
interface MyInterface {}
Output:
obj1 instanceof Parent: true
obj1 instanceof Child: false
obj1 instanceof MyInterface: false
obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true
When using the instanceof
operator, keep in mind that null
is not an instance of anything.