【问题标题】:Inheritance and Instances Java继承和实例 Java
【发布时间】:2019-04-03 02:20:20
【问题描述】:

关于 Java 包:在每个类都有自己的 .java 文件的包中,是否可以在其外部使用受包限制的子类对象来初始化公共父类对象 包裹? To-wit:我可以在 Parent 中创建一个初始化自身的方法吗 与隐藏的子实例?

我知道“this.new Child()”有效,但前提是 child 是内部类。 我正在尝试真正练习正确的对象封装,因此我希望子类对其包之外的任何人都保持隐藏。

编辑:为了进一步澄清我的问题,我在父类和子类 ChildB() 中添加了 initWithAnyChild()。

例如:

package righthere;//Parent.java



 public class Parent{

   public Parent(){}


   public void initWithChildA(){ this.new ChildA(); }

   public Parent initWithAnyChild(/*An identifier*/){

       switch(/*identifier*/){

         case /*ChildA*/: return new ChildA();
         case /*ChildB*/: return new ChildB();

         default: break;
        }

       return null;
    }
 }

/***/

package righthere;//ChildA.java

 class ChildA extends Parent{

     //Implementation;
  }

/***/

package righthere;//ChildB.java

 class ChildB extends Parent{

      //Implementation;


 }

/***/

package somewhere;//Test.java

import righthere.*;

public class Test{



   Parent var1.initWithChildA(); //Would not work since ChildA is not an inner class.

   Parent var2 = var2.initWithAnyChild(/*ChildA*/)//Would this work?



  }

 /*Is initWithAnyChild() the better way to go about this? Or is there 
  *an easier way?
  */

【问题讨论】:

  • 你想创建一个内部类吗? ChildA 必须在 Parent 的定义内。
  • 您无法让new 返回除您命名的类之外的任何内容。工厂方法会起作用吗?这可以返回任何有效的返回类型。
  • @ScaryWombat 这不违反一些编程规范吗?
  • @markspace 对于您的第一个问题:不,每个子类都在其自己的 .java 文件中,但包是隐藏的。第二个:可能是工厂方法可以工作,但我想看看是否有某种方法可以使用“新”或某种简单的初始化形式。
  • 所以你想要package-private 构造函数?

标签: java oop package


【解决方案1】:

回答我的问题:

使用我的示例,父类中的方法“initWithAnyChild(/An identifier/)”有效,我可以在其中检索包私有子类并将其存储在公共父类变量中(多态性)并且能够在其包之外使用它。

也许我的问题太混乱而无法理解,或者我不够清楚?仍然道歉,这是我在这里的第一篇文章。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多