接口类型的应用:用于接口指向类型的子类对象
package com.sdut.day2;
interface USB
{
publicvoid open();
publicvoid close();
}
publicclass BookPC {
publicstaticvoid main(String[] args) {
useUSB(new Upan());
useUSB(new Mouse());
}
publicstaticvoid useUSB(USB u){//接口类型的引用,用于指向接口的子类对象
u.open();
u.close();
}
}
class Upanimplements USB{
publicvoid open(){
System.out.println("upan open");
}
publicvoid close(){
System.out.println("upan close");
}
}
class Mouseimplements USB{
publicvoid open(){
System.out.println("mouse open");
}
publicvoid close(){
System.out.println("mouse close");
}
}
多态
多态的好处:提高的了代码的重用
多态的条件:子类要继承父类或者实现接口,并且覆盖父类后者接口中的方法
多态的弊端:父类的引用不能实现子类所特有的功能
转型:向上转型,向下转型
向上转型:Animal a = new Cat();限制特有的功能,实现代码重用
向下转型:Cat c = (Cat) a;可以使用特有的功能
类型判断
Public static voidmethod (Animal a)
{
a. eat();
//判断a的类型
If(a instance of(Cat)){
Cat c = (Cat) a
c.catchMouse();
}
If(a instance of Dog){//只能用于引用类型的判断
Dog d = (Dog) a ;
d.lookHome();
}
}
通常在向下转型前用于健壮性的判断
多态:
成员变量 覆盖只发生在函数不会发生在变量上
编译时:参考引用型变量所属类中是否有调用的成员变量,有则编译通过,没有则编译失败
运行时:参考引用型变量所属类中是否有调用的成员变量,并运行该所属类中的成员变量。
简单说:编译和运行都看等号左边
成员函数(非静态):当子类和父类有相同的方法,子类会覆盖父类的方法
编译时:参考引用类型变量所属类中是否有调用的函数,有的话则编译通过,没有则编译失败
运行时:参考的是对象所属的类中是否有调用函数。
简单说:编译看左边,运行看右边
静态函数:
编译时:参考引用型变量所属类中是否有调用的静态方法
运行时:参考引用型变量所属类中是否有调用的静态方法
简单说:编译和运行都看左边
对于静态方法:类可以直接调用,因为静态方法在程序运行时,自动加载
abstractclass Animal{
abstractvoid eat();
}
class Catextends Animal{
publicvoid eat(){
System.out.println("吃鱼");
}
publicvoid catchMouse(){
System.out.println("捉老鼠");
}
}
class Dogextends Animal{
publicvoid eat (){
System.out.println("吃骨头");
}
publicvoid lookHome(){
System.out.println("看家");
}
}
publicclass DUOTai {
publicstaticvoid main(String[] args) {
Cat c =new Cat ();
Dog d =new Dog()
;
Method(c);
Method(d);
}
publicstaticvoid Method(Animal animal){//多态一个对象两种邢台
animal.eat();
}
内部类
内部类的优点:当外部类有私有属性时,内部类可以直接访问外部类的私有属性和方法
外部类要访问内部类必须建立该内部类的对象,通过对象来访问该该内部类的成员。
内部类一般用于类的设计
分析事物时,发现该事物还有事物,而且这个事物还有访问被描述事物的内容。这时候就是还有事物定义成内部类来描述
如果内部类是静态的,相当于外部类Other.Inner in =new Other.Inner();
如果内部类中方法是静态的,该内部类必须是静态的
为什么内部类可以访问外部类的成员呢?
那是因为内部类持有了外部类的引用,外部类名.this
内部类在局部位置上只能访问局部中本final修饰的局部变量
class Other
{
privatestaticintnum = 8;
staticclass Inner
{
staticvoid show()
{
System.out.println("内部类"+num);
}
}
publicvoid method()
{
Inner in=new Inner();
in.show();
}
}
publicclass NeiBu {
publicstaticvoid main(String[] args) {
// Other o =new Other ();
// o.method();//间接访问内部类
// Other.Innerin = new Other().new Inner();//直接访问格式
// in.show();
Other.Innerin =new Other.Inner();
in.show();
}
匿名内部类:
就是内部类的简写格式
New 父类或者接口 {
重写的方法
}
interface Inter
{
void show1();
voidshow2();
}
class Outer
{
class Innerimplements Inter
{
publicvoid show1()
{
}
publicvoid show2()
{
}
}
publicvoid method()
{
// Innerin = new Inner();
// in.show1();
// in.show2();
new Inter()//匿名内部类,new一个借口和下面内容共同构成一个子类对象
{
publicvoid show1()
{
}
publicvoid show2(){
}
}.show1();
}
}