首页 > 解决方案 > 超类 obj = 新子类();意义和铸造

问题描述

如果我有超类(动物)和子类(猫)。

第三点是什么意思?什么时候我们必须施放?

  1. Cat obj = new Cat();意味着从 Cat 类创建一个对象

  2. Animal obj = new Animal();意味着从 Animal 类创建一个对象

  3. Animal obj = new Cat();

标签: javainheritance

解决方案


首先让我们了解类、引用和对象。假设我们有一个名为SomeClass

SomeClass ref = new SomeClass();

上面我们在堆中创建了一个 SomeClass 的对象,并且引用变量引用了它。我们将引用变量命名为ref。对象存在于堆中,我们可以使用引用访问它。所以对象类型是实际的类(new已应用关键字)。引用变量类型可以是实际类或其父类。

现在让我们看看继承的关系。从另一个类继承的类共享子-父关系。Child 继承其 Parent 的行为,然后可以覆盖一些行为,也可以添加一些额外的行为。因此,子对象可以在预期父对象的任何地方使用,因为子对象具有其父对象的所有行为,因此调用父对象中存在的任何行为都将由子对象处理。

父类不知道其子类的附加行为(子类是稍后编写的。)因此,父类的对象不能在预期有子类对象的地方使用(如果在父类上调用了子类的附加行为反对,则不会兑现)。

现在让我们假设我们有类ParentClassChildClass这样ChildClass inherits ParentClass

ParentClass reference =  new ParentClass(); // Valid
ParentClass reference = new ChildClass(); //Valid
ChildClass reference = new ChildClass(); //Valid
ChildClass reference = new ParentClass();// Not Valid.

注意 ParentClass 参考 = new ChildClass(); // 这里 Object 是 ChildClass 类型,Reference 是 ParentClass 类型。

现在什么时候投。任何期望 ParentClass 对象的地方,都不需要强制转换,(ParentClass 或 ChildClass 的)对象都可以。任何期望 ChildClass 类型的对象的地方,但如果我们有如下情况,则需要强制转换。

public void someMethod(ChildClass expected){
    //some implementation
}
ParentClass ref = new ChildClass();
someMethod(ref);//Invalid : Compilation Issue 
someMethod((ChildClass)ref);// Valid
ParentClass anotherRef = new ParentClass();
someMethod(anotherRef); // Invalid : Compilation Issue
someMethod((ChildClass)ref); //Invalid, compiles but Runtime it will fail. 

拇指规则:孩子是孩子,孩子是父母,父母是父母,父母不是孩子。

另一个理解的例子。

public abstract class List{
    public abstract void add(int element);
    public abstract void remove(int element);
   public int size();
}

public class Application{
    private  List listReference;
    public void setList(List ref){
         listReference = ref;
    }
}

//Now you may create sub classes as below 
public class ArrayList extends List{
     // all the abstract methods of List have been implemented 
}

public class LinkedList extends List{
    //all the abstract methods of List have been implemented
}

现在在 main 方法中,您可以传递 ArrayList 或 LinkedList 或任何其他实现。

public class Init{
    public static void main(String[] args){
         Application app = new Application ();
         app.setList(new LinkedList());
         //or you can set it like this
         List listRef = bew ArrayList();
         app.setList(listRef);
         //or you can set it like this
         LinkedList linkedListRef = new LinkedLiet();
         app.setList(linkedListRef);
    }
}

请注意,该方法setList()接受 List 类型的引用,我们可以提供 List 抽象的任何实现。这导致了灵活的设计。类应该依赖于抽象。接口编程是一种设计原则,它使应用程序代码易于维护。


推荐阅读