Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Adding fields and methods to existing Class?

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?

like image 756
Pots Spi Avatar asked Dec 05 '12 19:12

Pots Spi


People also ask

Can a subclass add new fields new methods?

► Each subclass can be a superclass of future subclasses, forming a class hierarchy. ► A subclass can add its own fields and methods.

What are fields and methods of a class in Java?

A field is a member variable that belongs to a class. A method is a set of java commands referred to by name. You are able to execute all the commands by using the name of the method. Methods can take values as parameters and return a value as a result.

Can a method extend a class?

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called.


2 Answers

You can create a class that extends the one you wish to add functionality to:

public class sub extends Original{  ... } 

To access any of the private variables in the superclass, if there aren't getter methods, you can change them from "private" to "protected" and be able to reference them normally.

Hope that helps!

like image 54
awolfe91 Avatar answered Sep 22 '22 17:09

awolfe91


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; } 
like image 34
Jacob Schoen Avatar answered Sep 20 '22 17:09

Jacob Schoen