class component1
{
component1( ) 
{
System.out.println("component1");
}
}
class component2
{
component2( )
{
System.out.println("component2");
}
}
class Root  
{
    component1 x=new component1( );//为什么不可直接用new component1( );
component2 y=new component2( );
Root( )
{
System.out.println("Root");
}
}
class Stem extends Root
{
Stem( )
{
System.out.println("Stem");
}
public static void main(String[ ] args)
{
new Stem( );//为什么在这里又可以啊?
    }
}
刚刚接触java,学到了继承,关于new的使用有点不大懂,希望大侠们帮一帮啊!
在一本书中看到可以直接用new **(),那为什么上面component那个地方不行啊?而下面stem那个地方又行了!
谢谢

解决方案 »

  1.   

    应该可以的
    请明确访问权限,private ,protected还是默认,public的
    请确保构造器能在其他类中访问main函数是static的
    是独立于对象的,是类的
      

  2.   

    楼主,还是排下版吧,
    我试了下,没你说的问题class component1 {
    component1() {
    System.out.println("component1");
    }
    }class component2 {
    component2() {
    System.out.println("component2");
    }
    }class Root {
    component1 x = new component1();//为什么不可直接用new component1( ); 
    component2 y = new component2(); Root() {
    System.out.println("Root");
    }
    }class Stem extends Root {
    Stem() {
    System.out.println("Stem");
    } public static void main(String[] args) {
    new Stem();//为什么在这里又可以啊? 
    }
      

  3.   

    一个类的{}中只能有属性,构造,方法
         component1 x=new component1( );x代表属性  new component1代表一个对象
         你单纯写个对象说明什么?
      

  4.   

        我形象一点给你解释一下,直接new XX()建立的是一个没有“名字”的实例对象,一般只用一次,因为,再想处理这个对象时,虽然它可能还存在,但是你找不到它了,因为你没给他指定一个“名字”,你再new一个也不一定是原来的它了。你如果是这样:
    component1 x=new component1( );//再想调用名字为“x”的component1类的对象,就方便了。
        这么说很不专业,但是我想可能更形象一点。
      

  5.   

    而且
    component1 x=new component1( );//为什么不可直接用new component1( ); 
    他是Root类的一个类型为类的属性,定义一个属性必须指明他的类型啊
      

  6.   

    而且 
    component1 x=new component1( );//为什么不可直接用new component1( ); 这里是可以用的
    只是前面申明了一个变量去接收这个对象 
    后面一般是申明一个对象做方法的参数