3.Java值传递与引用传递( 七 )


如下,指向类,类继承自,则与为true.
public class Person {}-------------------------------public class Teacher extends Person {}----------------------------------------public class Student extends Person {}-------------------------------------------public class Application {public static void main(String[] args) {Object object = new Student(); //这里object引用指向了Student类,则可以视作是Student的实例化对象System.out.println(object instanceof Person);//true,System.out.println(object instanceof Teacher); //falseSystem.out.println(object instanceof Student); //trueSystem.out.println(object instanceof Object); //trueSystem.out.println(object instanceof String); //false}}
再例如:
public class Application {public static void main(String[] args) {Person person = new Student();System.out.println(person instanceof Object); //trueSystem.out.println(person instanceof Student); //truePerson p = new Person();System.out.println(p instanceof Object); //trueSystem.out.println(p instanceof Student); //false}}
10.Java类型转换
public class Person {public void run(){System.out.println("父类的run方法");}}------------------------------------------------public class Student extends Person {public void go(){System.out.println("子类的go方法");}}----------------------------------------------------public class Application {public static void main(String[] args) {Person person = new Student();//这里是父类转换成子类,高转低,会丢失父类被子类所重写掉的方法//person.go();//编译不通过,报错Student student = (Student)person; //将父类向下强转成子类就可以使用子类的方法了student.run();student.go();//或者( (Student) person).go();( (Student) person).run();}}/*父类的run方法子类的go方法*/
题外话:另外,父类的引用指向子类,这个是向下转型,会丢失父类被子类重写的方法,也就是Java重写的思想,肯定只会调用子类重写的方法 。
如果是向上转型,比如:
public class Application {public static void main(String[] args) {Student student = new Student();Person person = student;//这里是子类转父类,可能会丢失自己本来的一些方法,也就是无法使用子类的独特方法}}
成员变量,静态方法看左边(成员变量和静态方法编译和运行都看左边);非静态方法:编译看左边,运行看右边 。针对这种说法解释下,成员变量,静态方法,这个不叫多态,多态与属性没关系,与,,final修饰的方法也没关系,所以一致看左边,否则即使多态,或者重写,不是重载,那么看右边 。
11.关键字详解
修饰方法的话则成为静态方法,修饰属性则成为静态属性 。
我们可以一句话来概括:方便在没有创建对象的情况下来进行调用,也就是说:被关键字修饰的不需要创建对象去调用,直接根据类名就可以去访问 。
静态变量存放在方法区中,并且是被所有线程所共享的 。静态变量随着类的加载而存在随着类的消失而消失,静态变量可以被对象(实例化后的对象)调用,也可以用类名调用 。(推荐用类名调用)
被修饰的成员变量叫做静态变量,也叫做类变量,说明这个变量是属于这个类的,而不是属于是对象,没有被修饰的成员变量叫做实例变量,说明这个变量是属于某个具体的对象的 。
1)静态属性
public class Student {private static int age;//静态的变量private double score;//非静态的变量public static void main(String[] args) {Student student = new Student();student.age=1;student.score=0.1;//上面通过实例化后可以调用属性直接赋值//但如果直接用类呢Student.age=2; //如果是静态变量,推荐直接这样用类去访问Student.score=2.5; //这里报错,提示不能引用非静态字段“score”}}