开发者

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

开发者 https://www.devze.com 2023-02-19 21:10 出处:网络
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 also holds base class
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 also holds base class  
  ab.a();
  ab.ma();
 }
 public void m()
 {
  System.out.println("Base class method");
 }
}

class amit extends arijit
{
 public void a()
 {
  S开发者_StackOverflowystem.out.println("Sub Class method");
  m();
 }
}


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.


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 :)


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消