我是Java的新手,对不起,如果这是一个愚蠢的问题,但它真的让我烦恼。我无法在互联网上的任何地方找到真正的答案,可能是因为我不知道如何在短期内提出问题。
我见过老师使用Interface或Parent类名作为数据类型来引用obj的教程。
如果我的问题令人困惑,此代码将更好地解释我的问题:
Runnable obj = new Thread();
/*instead of*/
Thread obj = new Thread();
这也适用于父类:
public class A{}
public class B extends A{}
A obj = new B();
我知道对象是由" new Class()"在堆中创建的。语法和该变量实际上并不包含对象,而是包含对象的位置。该引用变量还有规则"数据类型"。 我无法绕过去做类似的事情:
C obj = new B();
因此规则规定"数据类型"必须是要实例化的类的part(接口,父)。 为什么这是一个选择? 为什么人们这样做? 我也应该这样做吗? 什么是上帝? 所有这些都有充分的理由(更大的图片),还是Java提供的随机(更多选项)功能?
修改
我是Stackoverflow的新手,所以我在不知不觉中将这篇文章标记为重复一个,它不是重复的。
如果像我这样的人碰到同样的问题并且不知道如何谷歌出来,我会更新这个,因为不熟悉/未知的概念名称/术语。 现在一切都清楚了,让我们跳到启蒙之中。
当我们使用Interface或Parent类作为引用变量的数据类型时 我们告诉Java创建一个将被修剪的对象(据我所知),并且只包含我们用作数据类型的Interface或Parent类中存在的属性和方法。
我将ArrayList类作为示例代码:
//dont pay attention to the generics,im using it for a good practice
Collection<Integer> obj = new ArrayList<>();
/*This works! Because add method is defined in Collection Interface
aswell as ArrayList class duhhh...*/
obj.add(3);
/*This gives compilation time error.Because method doesnt exist in
Collection interface but it is valid method in ArrayList class*/
obj.indexOf(3);
父类DataType也是一个例子:
public class foo {
public void sayHarro() {
System.out.println("Harro from foo");
}
public void stateYourGendre() {
System.out.println("I indentify myself as fooSexual");
}
}
public class bar extends foo {
public void sayHarro() {
System.out.println("Harro from bar");
}
public void madeInBar() {
System.out.println("im genuine");
}
}
public class test {
public static void main(String[] args) {
foo obj = new bar();
/*No Problem!Everything is legit.Method exists in foo!
Outputs: Harro from bar*/
obj.sayHarro();
/*
*No Problem! Method exists in foo and is inherited, though not
*overwritten (redeclared in bar).
*Outouts: I indentify myself as fooSexual
*/
obj.stateYourGendre();
/*
*Now we have a Compile time error, because method doesnt exist
*in provided DataType of the reference variable though it's
*valid bar class method.
*/
obj.madeInBar();
}
}
现在至少对我来说一切都很清楚了,我希望你也能这样。虽然现在出现了一个我没有安装的问题。
另请注意上面我说它会被削减,但我添加了额外的注释 &#34;据我理解&#34; !重要的是要注意,直到新问题由具有实际知识的人回答。因为如果不修剪所有这些东西只是为了制作更严格和更加严格的代码。 如果有的话,我真的很想知道整个概念的名称。 可能堆在你身边!