Java:向现有Class添加字段和方法? [英] Java: Adding fields and methods to existing Class?

查看:1121
本文介绍了Java:向现有Class添加字段和方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,是否有一种向现有类添加某些字段和方法的方法?
我想要的是我有一个类导入到我的代码中,我需要添加一些从现有字段派生的字段及其返回方法。
有没有办法做到这一点?

Is there, in Java, a way to add some fields and methods to an existing class? What I want is that I have a class imported to my code, and I need to add some fields, derived from the existing fields, and their returning methods. Is there any way to do this?

推荐答案

您可以用Java扩展类。例如:

You can extend classes in Java. For Example:

public class A {

  private String name;

  public A(String name){
    this.name = name;
  }

  public String getName(){
    return this.name;
  }

  public void setName(String name) {
    this.name = name;
  }

}

public class B extends A {
  private String title;

  public B(String name, String title){
    super(name); //calls the constructor in the parent class to initialize the name
    this.title= title;
  }      

  public String getTitle(){
    return this.title;
  }

  public void setTitle(String title) {
    this.title= title;
  }
}

现在 B 可以访问 A 中的公共字段:

Now instances of B can access the public fields in A:

B b = new B("Test");
String name = b.getName();
String title = b.getTitle();

有关更详细的教程,请查看继承(Java教程>学习Java语言>接口和继承)

For more detailed tutorial take a look at Inheritance (The Java Tutorials > Learning the Java Language > Interfaces and Inheritance).

编辑:如果类 A 有一个构造函数,如:

If class A has a constructor like:

public A (String name, String name2){
  this.name = name;
  this.name2 = name2;
}

然后在班级 B 你有:

public B(String name, String name2, String title){
  super(name, name2); //calls the constructor in the A 
  this.title= title;
}

这篇关于Java:向现有Class添加字段和方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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