Java - Abstract class to contain variables?

Is it good practice to let abstract classes define instance variables?

public abstract class ExternalScript extends Script {

    String source;

    public abstract void setSource(String file);

    public abstract String getSource();
}

The sub class, ExternalJavaScript.class, would then automatically get the source variable but I feel it's easier to read the code if all the sub classes themselves define the source, instead of from inheritance.

What is your advice?

/Adam


Asked by: Fiona832 | Posted: 21-01-2022






Answer 1

I would have thought that something like this would be much better, since you're adding a variable, so why not restrict access and make it cleaner? Your getter/setters should do what they say on the tin.

public abstract class ExternalScript extends Script {

    private String source;

    public void setSource(String file) {
        source = file;
    }

    public String getSource() {
        return source;
    }
}

Bringing this back to the question, do you ever bother looking at where the getter/setter code is when reading it? If they all do getting and setting then you don't need to worry about what the function 'does' when reading the code. There are a few other reasons to think about too:

  • If source was protected (so accessible by subclasses) then code gets messy: who's changing the variables? When it's an object it then becomes hard when you need to refactor, whereas a method tends to make this step easier.
  • If your getter/setter methods aren't getting and setting, then describe them as something else.

Always think whether your class is really a different thing or not, and that should help decide whether you need anything more.

Answered by: Kimberly304 | Posted: 22-02-2022



Answer 2

Sure.. Why not?
Abstract base classes are just a convenience to house behavior and data common to 2 or more classes in a single place for efficiency of storage and maintenance. Its an implementation detail.
Take care however that you are not using an abstract base class where you should be using an interface. Refer to Interface vs Base class

Answered by: Max951 | Posted: 22-02-2022



Answer 3

Of course. The whole idea of abstract classes is that they can contain some behaviour or data which you require all sub-classes to contain. Think of the simple example of WheeledVehicle - it should have a numWheels member variable. You want all sub classes to have this variable. Remember that abstract classes are a very useful feature when developing APIs, as they can ensure that people who extend your API won't break it.

Answered by: Justin993 | Posted: 22-02-2022



Similar questions

java - Adding variables to abstract class or to the child class?

I have a dilemma with this, I am designing a project and basically it will have a baseclass -> entityclass relationship where the entity class inherits from the baseclass. Now the base class is abstract and would have something like: abstract class MyAbstractClass{ //All this methods need to be implemented abstract int getHouseId(int id); abstract string getHouseName(String s); } Then I ...


Java abstract class "instance variables"

I don't know if my mind just fools me or this is really not working. I need different type of Logging-classes so I created a abstract-class, the only definition that all classes will have the same is the way the writeToLog is handled: public abstract class LoggerTemplate { protected String filename ="log/"; protected File logfile; protected FileWriter fw; public void writeToLog(St...


java: abstract classes and its variables

I am fairly new to java so I tried to implement an example and use abstract classes but my lack of OO knowledge makes me wonder why I cannot use a private variable from the abstract class in a "concrete" class extending it. Here is my code: abstract class Equation{ private double[] c;//oefficient public static int degree(double[] coeff) { return coeff.length; } public abstrac...


Eclipse - Hover not showing variables in abstract Java class

I'm currently using Spring Tool Suite 2.9.2 (based off of Eclipse 3.x). In every class that I debug through, it has no issue with on-hover displaying the values of my variables. But, when I am in an abstract class, on-hover just displays the variable type and name. This is super frustrating to me, because the values get displayed in the Variables window. I usually go "Oh, I'm in an abstract class..." and ...


java - How to read and write to variables of an abstract class

Put simply, I have an abstract class containing several variables and methods. Other classes extend this abstract class, yet when I try to read the private variable in the abstract class by calling getter methods inside the abstract class, it returns null as the value of the variable. public class JavaApplication { public static void main(String[] args) { NewClass1 n1 = new NewClass1(); ...


java - When a class extends from an abstract class then how to access its private variables?

I have an abstract class A and class B extends from it.I made those variables private and its fine. public abstract class A { private String name; private String location; public A(String name,String location) { this.name = name; this.location = location; } public String getName() { return name; } public void setName(String name) { ...


java - Abstract class to hold common member variables

Can we use abstract class to just hold common member variables which are autowired. This was the classes extending the abstract class need not declare the member fields again. Is this a good design pattern ? If not what is a better way to achieve this ? Note : The abstract class does not have any methods. abstract class Abs { @autowired protected ClassA varA; @Autowired protected ClassB...


java - How can I inject local variables of a static method inside an abstract class using Spring?

I'm new to Spring and ran into this problem.I tried using @Autowired on the method but it didnt work,on the variables I get the error "The annotation @Autowired is disallowed for this location" from eclipse. I have the required beans created in the xml. Below is the code,this method is inside an abstract class.. private static HttpResponse rawExecuteReqeust(HttpUriRequest request) throws ClientProto...


Abstract class in Java with global variables aren't setting?

I've got 2 classes setup, both extending a Module class. I'm trying to set 2 integers in one of them and using 2 integers in the other. However when I execute everything, it does get set (I know because of debugging) but when the method for 'printing' runs, it's still 0. I don't know what I'm doing wrong though. Module Class: public abstract class Module { protected int min, max; }


Abstract Classes in Java and their object variables

i am wondering what happens with object variables in abstract classes in Java. For example if have this abstract class: public abstract class BaseClass{ private int[] myNumbers; public Baseclass(int length){ myNumbers = new int[length]; } public boolean isOne(int index){ return myNumbers[index] == 1; } } and i have this real class which extends the BaseClass: publi...


java - Large Inner classes and private variables

One thing I've run into a few times is a service class (like a JBoss service) that has gotten overly large due to helper inner classes. I've yet to find a good way to break the class out. These helpers are usually threads. Here's an example: /** Asset service keeps track of the metadata about assets that live on other * systems. Complications include the fact the assets have a lifecycle and their * physic...


Library that subverts java access control and lets me access private member variables?

Can anoyne recommend a good library that will let me easily read/write private member fields of a class? I was looking through apache commons, but couldnt see it. I must be getting blind ? Edit: Asking questions on the border of legalities always give these questions of "why"? I am writing several javarebel plugins for hotswapping classes. Accessing private variables is only step 1, I might even have to replace imp...


Java session variables

I'm hearing that some people believe storing info on the server in a session is a bad idea, that its not secure. As a result, in a multi-page business process function, the application is writing data to a db, then retrieving the info when its needed. Is there something necessarily unsafe about storing private info in a session?


Simple Variables in Java & C++

I saw this sentence in some matrials: "In Java, simple data types such as int and char operate just as in C." I am wondering that actually they are different in Java & C++? In C++, simple variables like the primitives in Java are assigned a memory address as well, so these primitive types in C++ can have a pointer as well. However primitives in Java are not assigned a memory address like Objects...


variables - What is the purpose of long, double, byte, char in Java?

So I'm learning java, and I have a question. It seems that the types int, boolean and string will be good for just about everything I'll ever need in terms of variables, except perhaps float could be used when decimal numbers are needed in a number. My question is, are the other types such as long, double, byte, char


java - Can you define your own template variables in Eclipse

In Eclipse there are templates that help you by automatically inserting some code or comments. You can edit these templates yourself via Preferences > Java > Editor > Templates. There are so-called "template variables" that you can use to make these templates a little smarter. For instance, there is the ${see_to_overridden} variable that inserts "@see my.package.name.SpuerclassName#methodName(int, my.other.package....


Does it help GC to null local variables in Java

I was 'forced' to add myLocalVar = null; statement into finally clause just before leaving method. Reason is to help GC. I was told I will get SMS's during night when server crashes next time, so I better did it :-). I think this is pointless, as myLocalVar is scoped to method, and will be 'lost' as soon as method exits. Extra nulling just pollutes the code, but is harmless otherwise. My questi...


java - Static variables and methods

I ran across a class that was set up like this: public class MyClass { private static boolean started = false; private MyClass(){ } public static void doSomething(){ if(started){ return; } started = true; //code below that is only supposed to run //run if not started } } My understanding with static methods is that you should not use class variables i...


java - Should all methods be static if their class has no member variables

I've just had an argument with someone I work with and it's really bugging me. If you have a class which just has methods like calculateRisk or/and calculatePrice, the class is immutable and has no member variables, should the methods be static so as not to have to create an instance of the class each time. I use the following example: public class CalcService { public int calcPr...


Can using too many static variables cause a memory leak in Java?

If my application has too many static variables or methods, then as per definition they will be stored in heap. Please correct me if I am wrong 1) Will these variables be on heap until application is closed? 2) Will they be available for GC at any time? If not can I say it is a memory leak?






Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top