java 如何创建类的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5609960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:53:42  来源:igfitidea点击:

How to create object of class

java

提问by Jonah

I think this explains my question well enough:

我认为这很好地解释了我的问题:

public class Model {
    public static Model [] findAllBySQL(String SQL){
        //this is simplified.  It should really query the DB and then fill model(s) with the DB values, and return the model(s).  sql query can return more than one row
        return new this(); //sytax error here
    }
}


public class UserModel extends Model {

}


UserModel.findAllBySQL("firstname=john") //How do I design the above so this returns a UserModel object?

I'm relatively new to Java. My background is mostly PHP. I am trying to create a simple home-made active record system.. I know this is recreating the wheel, but that's how I learn :)

我对 Java 比较陌生。我的背景主要是 PHP。我正在尝试创建一个简单的自制活动记录系统..我知道这是重新创建轮子,但这就是我学习的方式:)

EDIT: Most of you guys misunderstood me. I know how to simple to new UserModel(). I changed the code to make it more clear.

编辑:你们大多数人误解了我。我知道如何简单new UserModel()。我更改了代码以使其更清晰。

回答by Harry Joy

Why not simply use newoperator as

为什么不简单地使用new运算符作为

UserModel userModel = new UserModel();

To know different ways to create an object in java see this thread: what-are-all-the-different-ways-to-create-an-object-in-java

要了解在 Java 中创建对象的不同方法,请参阅此线程:what-are-all-the-different-ways-to-create-an-object-in-java



Edit

编辑

Based on your edit what you can do is?

根据您的编辑,您可以做什么?

public static Model findBySQL(String SQL){
        Model model = new Model();
        // Now query in db to get data. then use setter methods of Model to set data in object
        // i.e. model.setXXX(XXX);
        // and finally return that model object.
        return model;
    }


Edit 2

编辑 2

UserModel could have getFullName() which concatenates the first name with the last name from the db. I would need to be able to access this method straight away on the object returned from findBySQL

UserModel 可能有 getFullName() ,它将名字与来自数据库的姓氏连接起来。我需要能够在从 findBySQL 返回的对象上立即访问此方法

You can try like this: in UserModel,

你可以这样尝试:在 UserModel 中,

public String getFullName(){
    Model model = findBySql("str='str'");
    return model.getFirstName()+"  "+model.getLastName();
}

回答by MByD

You should use a constructor:

您应该使用构造函数:

public class Model {
    //Constructor
    public Model()
    {
    // Do initialization stuff here
    }
}


public class UserModel extends Model {
    //Constructor
    public UserModel()
    {
    // Do initialization stuff here
    }
}

To create new object, you call it like that:

要创建新对象,您可以这样称呼它:

UserModel myUserModel;    // Declare new object reference
myUserModel = new UserModel();   // create new object of this class

Edit:

编辑:

If you declare the method as a method returning array of Models, you can't return a single model, you may return a Modelarray with one Model, but not a single object.

如果将该方法声明为返回Models数组的方法,则不能返回单个模型,您可以返回一个Model包含 1的数组Model,但不能返回单个对象。

For example

例如

public static Model [] findAllBySQL(String SQL){
    // find how many models do you have
    Model[] models = new Model[numberOfModels];
    for (Model model : models)
    {
         model = new Model();
         //do what you want with it...
    }
    return models; //sytax error here
}

回答by Vincent Ramdhanie

Sounds like you need the Factory Method Pattern. If you have a Model super class and several types of Models then you can encapsulate the object creation in a ModelFactory class with a createModel() method that returns the appropriate type of Model based on the parameter to the method.

听起来你需要工厂方法模式。如果您有一个 Model 超类和多种类型的模型,那么您可以使用 createModel() 方法将对象创建封装在 ModelFactory 类中,该方法根据方法的参数返回适当类型的模型。

 class ModelFactory(){
       public Model createModel(String sql, String type){
            //execute SQL

            if(type.equals("user")){
                 UserModel model = new UserModel();
                 //set the attributes here
                 return model;
            }

            if(type.equals("other")){
                 OtherModel model = new OtherModel();
                 //set attributes here
                 return model;
            }

             //etc
       }
 }

To actually get a Model object you can now:

要实际获取 Model 对象,您现在可以:

       ModelFactory factory = new ModelFactory();
       Model m = factory.createModel("select * from mytable", "user");

回答by StKiller

You can do it in this way :

你可以这样做:

import java.util.ArrayList;
import java.util.List;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

public class Generics<T> {

    //method that returns a generic list
    public List<T> findAllBySQL(String SQL) {
        throw new NotImplementedException();
    }

    public static void main(String[] args) {
        //base class that returns a list of childs
        Generics result = new ExtendedGenerics(null);
        List<ExtendedGenerics> genericArray = result.findAllBySQL(null);
        for (ExtendedGenerics item : genericArray) {
            System.out.println(item);
        }
    }
}

//extend base class and specify generic type
class ExtendedGenerics extends Generics<ExtendedGenerics> {

    private String myMessage;

    public ExtendedGenerics(String yourMessage) {
        myMessage = yourMessage;
    }

    @Override
    //overriding base method, so it return a instances list of this class 
    public List<ExtendedGenerics> findAllBySQL(String SQL) {
        ArrayList<ExtendedGenerics> result = new ArrayList<ExtendedGenerics>();
        result.add(new ExtendedGenerics("I am first"));
        result.add(new ExtendedGenerics("I am second"));
        result.add(new ExtendedGenerics("I am third"));
        return result;
    }

    @Override
    public String toString() {
        return "ExtendedGenerics{" + myMessage + '}';
    }
}

So in this way no casting in necessary. This is the output of the code :

所以用这种方式不需要铸造。这是代码的输出:

ExtendedGenerics{I am first}
ExtendedGenerics{I am second}
ExtendedGenerics{I am third}

回答by yegor256

You can use Factory Methodplus Java Generics:

您可以使用工厂方法加上Java 泛型

public class Model {
  public static <T> T[] findAllBySQL(String SQL, Class<T extends Model> type) {
    T[] result = new T[123];
    for (int i = 0; i < 123; i++) {
      result[i] = type.newInstance();
    }
    return result;
  }
}
public class UserModel extends Model {
}
Model[] rowset = UserModel.findAllBySQL("firstname=john", UserModel.class); 

I assume this is the alternative of a plain simple PHP construct:

我认为这是一个简单的 PHP 构造的替代方案:

new $type();

回答by Mark Mooibroek

This is how you use this

这就是你如何使用它

UserModel m = new UserModel();

UserModel m now has all functions/values from
UserModel + the functions/values from Model.

UserModel m 现在拥有来自
UserModel 的所有函数/值+ 来自 Model 的函数/值。

Example

例子

public class Model {
    public Model()
    {
    // Do initialization stuff here
    }

    public getVal(){
        return 1+1;
    }
}


public class UserModel extends Model {
    public UserModel()
    {
    // Do initialization stuff here
    }

    public getValue2(){
        return 2+2;
    }
}


UserModel m = new UserModel();

m.getVal(); //Will return 2
m.getValue2(); // Will return 4