How is it possible to create a sub class object within it's base class?

后端 未结 5 1627
自闭症患者
自闭症患者 2021-01-25 17:38
class arijit
{
 public static void main(String args[])
 {
  System.out.println(\"Base class main\");
  amit ab=new amit(); //how is it possible as the sub class object a         


        
相关标签:
5条回答
  • 2021-01-25 18:18

    Its simple as you can create an object in the class of the same class type, you can create its subclass type too.

    0 讨论(0)
  • 2021-01-25 18:20

    Perhaps you need to distinguish compile time from runtime.

    At compile time the structure of arijit is well-known. It does not matter that halfway in the class, in main, a subclass is used, as that is a runtime thing.

    But I admit, the Java compiler is not all that stupid :)

    0 讨论(0)
  • 2021-01-25 18:29

    The crux of your question seems to be that you're creating an instance of the amit class within the main method of its base class, arijit, and you're wondering how that's possible.

    Why wouldn't it be possible? Your main method references the subclass by name, so it's just like any other class from that point of view. You can do it in non-static members, too, if you like.

    Architecturally, it usually indicates that there's a problem with your structure if the base class knows the intimate details (like the names) of its subclasses; that's not the usual way 'round of things.

    0 讨论(0)
  • 2021-01-25 18:31

    When you compile your program two .class files are formed,namely arijit.class and amit.class. So when your program is being interpreted ,interpreter knows about both the .class files and hence you can create Objects like that.

    0 讨论(0)
  • 2021-01-25 18:31

    The place you can't create a sub-class in the parent class is in the constructor.

    0 讨论(0)
提交回复
热议问题