gpt4 book ai didi

java - 如何构建只有一个区别的 3 个类

转载 作者:行者123 更新时间:2023-11-30 08:37:35 25 4
gpt4 key购买 nike

我有 3 个类需要用 Java 编写。为了便于讨论,它们被称为 Task1、Task2 和 Task3。

三个任务完全一样,只是它们是不同“类型”的任务。因此,Task1 的字段类型将为“Task1”,依此类推。

最初我写了三个类,只有这一点不同。但我认为最好编写一个基类 Task 并在三个子类中扩展这个类 [我显然对 Java 有点陌生]。

但是,我不知道该怎么做。

我的碱基调用如下所示:

package com.scoular.model;

public class TaskBase implements Serializable {

private static final long serialVersionUID = -5867831497684227875L;

private String unid;
private String type;
private Number order;

public TaskBase() {
}

public void create() {
try {
clear();
newNote = true;
Session session = Factory.getSession();
Date date = new Date();
crtDte = session.createDateTime(date);
crtUsr = session.getEffectiveUserName();
} catch (Exception e) {
XspOpenLogUtil.logError(e);
}
}

public void loadByUnid(String unid) {
...
}

public void loadValues(Document doc) {
...
}

private void clear() {
...
}

public boolean save() {

boolean tmpSave = true;

Document doc = null;
Session session = Factory.getSession();
Database PCDataDB = session.getDatabase(PCConfig.getpcDataDBpath());

if (newNote) {
doc = PCDataDB.createDocument();
doc.put("order", this.getNextOrder(doc));
} else {
doc = PCDataDB.getDocumentByUNID(unid);
}
doc.put("title", title);
doc.put("notes", notes);

doc.save();

return tmpSave;
}

// Getters and Setters for common fields

public String getUnid() {
return unid;
}

public void setUnid(String unid) {
this.unid = unid;
}

public String getType(String type) {
return type;
}

public void setType(String type) {
this.type = type;
}

public Number getOrder() {
return order;
}

public void setOrder(Number order) {
this.order = order;
}

}

我的父类(super class)看起来像这样:

package com.scoular.model;

import com.scoular.model.TaskBase;

public class Task extends TaskBase implements Serializable {

private static final long serialVersionUID = -5867831497684227875L;

// Custom Fields

public Task() {

super();
this.setType("Build");
}

}

我删掉了一些多余的代码。本质上我想我想要一个抽象类,因为我永远不会实例化 TaskBase。我知道我也可以通过实现来做到这一点,但我不太了解。

如有任何帮助,我们将不胜感激。

最佳答案

protected 字段可以从子类访问。因此,您可以使 type 字段 protected 并在子类中分配所需的值。

任务基类:

`public abstract class TaskBase implements Serializable {

private static final long serialVersionUID = -5867831497684227875L;

private String unid;
protected String type;
private Number order;

任务类:

public class Task extends TaskBase implements Serializable {

private static final long serialVersionUID = -5867831497684227875L;

// Custom Fields

public Task() {

super();
type = "build";
}

}

关于java - 如何构建只有一个区别的 3 个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37077922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com