第5.2章 java面向对象
多态
public class Application {
public static void main(String[] args) {
//一个对象的实际类型是可以确定的
//new Student();
//new Person()
//但是指向的引用类型就不确定了:父类的引用指向了子类
//Student能调用的方法都是自己的或者继承父类的!
Student s1=new Student();
//Person 父类,可以指向子类,但是不能调用子类的独有的方法
Person s2=new Student();
Object s3=new Student();
}
}
注意事项:
1.多态是方法的多态,属性没有多态
2.父类和子类有联系。 没有关系的比如String s=new Student(); 将会类型转换异常!!!
3.多态存在条件: 继承关系,方法需要重写,父类引用指向子类对象
4.static修饰的方法,属于类,它不属于实例
5.final 所修饰的方法是无法被继承的。该类已经无法改变了,因为它是一个常量类
6.private修饰的方法,子类将没有没有权限访问
1.instanceof
在这个代码里面 Person为父类,Teacher和Student继承了Person
public class Application {
public static void main(String[] args) {
Object object = new Student();
//可以使用instanceof关键来判断这个类型是否相似
System.out.println(object instanceof Student);//true
System.out.println(object instanceof Person);//true
System.out.println(object instanceof Object);//true
System.out.println(object instanceof Teacher);//false
System.out.println(object instanceof String);//false
System.out.println("==================================");
Person person=new Student();
System.out.println(person instanceof Student);//true
System.out.println(person instanceof Person);//true
System.out.println(person instanceof Object);//true
System.out.println(person instanceof Teacher);//false
//System.out.println(person instanceof String);//编译出错
System.out.println("==================================");
Student student=new Student();
System.out.println(student instanceof Student);//true
System.out.println(student instanceof Person);//true
System.out.println(student instanceof Object);//true
//System.out.println(student instanceof Teacher);//编译出错
//System.out.println(person instanceof String);//编译出错
}
}
2.类型转换
- 父类引用指向子类的对象
- 把子类转换为父类,低转高 为默认
- 吧父类转换为子类,高转低 需要使用强制转换
- 方便方法的调用,减少重复的代码
static关键详解
对于变量而言:
低于方法而言:
代码块:
导包时的使用:
抽象类
-
abstarct修饰符可以用来修饰方法也可也以修饰类,如果修饰方法,那么该方法就是抽象方法;如果修饰类那么该类就是抽象类
-
抽象类中可以没有没有抽象方法,但是有抽象方法的类一定要声明为抽象类
-
抽象类。不能使用new关键字来创建对象,它是用来让子类继承的。
-
抽象方法,只有方法的声明,没有方法的实现。它是用来让子类实现的。
-
子类进程抽象类,那么就必须也要实现抽象类没有实现的抽象方法,否则该子类也要声明为抽象类
接口
-
可以利用接口实现多继承
-
普通类:只有具体的实现
-
抽象类:具体时间和抽象方法(规范)都有
-
接口只有抽象方法(规范)
-
接口也不能被实例化,接口中没有构造方法
-
implements可以实现多个接口
-
声明接口的关键字:interface
四种内部类
- 成员内部类
- 静态内部类
- 局部内部类
注意:
1.一个java类里面只能有一个public class的类
方法里面:
- 匿名内部类