简体   繁体   English

如何从Java中的其他类创建对象

[英]How to create an object from a different class in java

I am pretty new to java, and was wondering how to create an object of a different class. 我对Java很陌生,想知道如何创建其他类的对象。 I would extend that class, however I am already extending another. 我会扩展该类,但是我已经扩展了另一类。 For example: 例如:

public class Dog extends Animal{
    //How do I create a "Chupacabra" object in here?
    Chupacabra jeff = new Chupacabra();
    //I've been doing this^, but it says "Cannot be resolved as type"
}

public class Chupacabra {

}

Or am I crazy? 还是我疯了? I know it doesn't make much sense to make a Chupacabra object in there, but... I need to. 我知道在其中制作Chupacabra对象没有多大意义,但...我需要。

public class Dog extends Animal{        
    Chupacabra ch = new Chupacabra(); //creating "Chupacabra" object
}

class Chupacabra {

}

You can't have two public classes under one .java name; 一个.java名称下不能有两个公共类。 so I removed 'public' from the second class. 所以我从第二堂课中删除了“公开”。

If you want, you can keep the second class as "Chupacabra.java" 如果需要,可以将第二个类保留为“ Chupacabra.java”

If I understand your question, and assuming Chupacabra is in the same package as Dog . 如果我理解您的问题,并假设ChupacabraDog放在同一个包装中。 You could use the default constructor like - 您可以使用默认的构造函数,例如-

public class Dog extends Animal{
  //How do I create a "Chupacabra" object in here?
  private Chupacabra myChupacabra = new Chupacabra();
}

If Chupacabra is in a different package from Dog then you will need to import Chupacabra . 如果ChupacabraDog包装不同,则您需要导入Chupacabra

If you want to merely have an instance of Chupacabra class inside of the Dog class, then you can declare it as an instance variable, as such: 如果您只想在Dog类中包含Chupacabra类的实例,则可以将其声明为实例变量,如下所示:

Dog.java : Dog.java

public class Dog extends Animal{
    Chupacabra myChupacabra = new Chupacabra();

    //...
}

Chupacabra.java : Chupacabra.java

public class Chupacabra {

}

Note that the Dog class needs to be declared in Dog.java and that the Chupacabra class needs to be declared in Chupacabra.java . 请注意, Dog类需要在Dog.java声明, Chupacabra类需要在Chupacabra.java声明。

For more information on declaring member variables in Java, please see the documentation . 有关在Java中声明成员变量的更多信息,请参见文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM