对引用和对象之间的关系一直不清晰 比如说 interface ListInterface<T>{
...
}class LList<T> implements ListInterface{
...
}
我这样生成对象: ListInterface<String> mylist = new LList(); 和这样生成对象:LList<String> mylist = new LList(); 有什么区别?我明白 ListInterface<String> mylist 是生成一个ListInterface的引用。
我也明白 new LList(); 是生成一个LList类型的对象。
但是我就是不明白 这个2个语句(in red)的区别
请指点 (同时请无视泛型)谢谢
...
}class LList<T> implements ListInterface{
...
}
我这样生成对象: ListInterface<String> mylist = new LList(); 和这样生成对象:LList<String> mylist = new LList(); 有什么区别?我明白 ListInterface<String> mylist 是生成一个ListInterface的引用。
我也明白 new LList(); 是生成一个LList类型的对象。
但是我就是不明白 这个2个语句(in red)的区别
请指点 (同时请无视泛型)谢谢
LList <String> mylist = new LList(); 同样的,右边申请new llist();然后分别把引用赋值给左边的定义。
interface Human{...}
class Student implements Human{...}Human wo = new Student();
Student wo = new Student();
/* 上面两句也是一样的?一点点区别也 没有的吗 请问?
}
class Sub extends Super{
}Super ref = new Sub();
ref是Super类型的变量(variable),或者称为引用(reference).该引用指向一个对象,这就是new Sub()创造的对象。
这个我懂 但是 Super ref = new Sub(); 和
Sub ref = new Sub(); 有什么区别呢? 是不是后者只能使用Super中的方法?那么再想问下 interface Super{}
class Sub implements Super{} 中Super ref = new Sub(); 和
Sub ref = new Sub(); 有什么区别呢?回答就结贴哇 谢谢
ref的类型是Super,所以只能用Super中定义的方法,或者Super的父类定义的方法。编译器会做检查。
Sub ref = new Sub();
ref的类型是Sub,当然是可以用Sub中定义的方法了。如果要确定ref到底是指向的什么类型的对象,使用ref.getClass().getName()来确定,不过这需要运行时确定。
ListInterface <String> mylist = new LList();
//不能访问LList中也就是不能访问子类中特定的一些方法和成员变量
LList <String> mylist = new LList();
//例如我门知道当我门用list去装对象的时候,一般都是List l = new ArrayList();//那为什么不用ArrayList al = new ArrayList();了,前着只能运用List借口中的一些方法,后着这可以运用其特有的方法,试想,当你在你个程序中,如果用到的都是List借口中的一些方法而并没有运用到ArrayList类中的特有方法,那么我就可以按前着定义,这样我门哪天想把他换成List l = new LinkedList()的话,则只需要改这一个地方,程序中的其他地方不需要改变。
class Student implements Human{...}Human wo = new Student();
Student wo = new Student();
/* 上面两句也是一样的?一点点区别也 没有的吗 请问?
-----------------------------------------
1、引用只有一个,就是new Student();看谁持有的问题。
2、持有的它的(引用)变量是父类/接口,则子类特性丧失。
3、语言角度看,这是多态问题;设计角度看,DIP(依赖倒置)/针对接口编程
------------------------------------------
不要学TIJ的搞法,mylist 你叫它“多态变量”。
理解多态的关键也就是“多态变量”和它持有的引用之间的关系问题,消息理解和动态绑定。
//接口
public interface In1 {
void show();
}
//测试面向接口编程
public class TestInterface
implements In1{
public static void main(String[] args) {
In1 a = new TestInterface();
a.show();
//两个效果一样,下面的强转也是强转的a指向的对象的类型。
TestInterface obj = (TestInterface)a;
obj.show();
} @Override
public void show() {
System.out.println("show in1");
}
}
例://写一个方法public void show(In1 aIn1){
aIn1.show();//不同的子类会对该接口的方法有自己的重写 这样就使传参方便,灵活 是不是这就是传说中的“面向接口编程”?
}