如何在其基类中创建子类对象? [英] How is it possible to create a sub class object within it's base class?

查看:59
本文介绍了如何在其基类中创建子类对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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()
 {
  System.out.println("Sub Class method");
  m();
 }
}

推荐答案

问题的症结似乎在于您正在 main 它的基类 arijit 的方法,您想知道这怎么可能.

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.

为什么不可能呢?您的 main 方法按名称引用该子类,因此从该角度来看,它就像其他任何类一样.如果愿意,您也可以在非静态成员中进行此操作.

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.

这篇关于如何在其基类中创建子类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆