Java: Adding fields and methods to existing Class?

后端 未结 4 737
终归单人心
终归单人心 2021-01-01 09:08

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

4条回答
  •  渐次进展
    2021-01-01 09:55

    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;
      }
    }
    

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

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

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

    Edit: If class A has a constructor like:

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

    then in class B you have:

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

提交回复
热议问题