Java abstract class getter

Right way to access fields of an abstract class?

I am trying to figure out what is the right way to access private fields of an abstract class and then use it in the class which is extending the abstract class. Below is my abstract class Process class (abstract):

public abstract class Process implements Runnable < private final Properties props; private final String processName; public Process(String processName, Properties props) < this.processName = processName; this.props = props; >public abstract void shutdown(); public Properties getProps() < return props; >public String getProcessName() < return processName; >> 

And below is one way of how I am extending my above abstract class and using props Properties object. ProcessA class:

public class ProcessA extends Process < private ProcessConsumerconsumer; public ProcessA(String processName, Properties props) < super(processName, props); >@Override public void run() < // is this the right way? String processName = getProcessName(); Properties props = getProps(); consumer = new ProcessConsumer<>(props); // .. some other code with try catch block // using processName and consumer > @Override public void shutdown() < consumer.wakeup(); >> 

And below is second way of how I can extending my above abstract class and using properties object. ProcessB class:

public class ProcessB extends Process < private final ProcessConsumerconsumer; public ProcessB(String processName, Properties props) < super(processName, props); // is this the right way to use props object? this.consumer = new ProcessConsumer<>(props); > @Override public void run() < String processName = getProcessName(); // .. some other code with try catch block // using processName and consumer >@Override public void shutdown() < consumer.wakeup(); >> 

I want to use props Properties in making ProcessConsumer object but I am confuse what is the right way to use props object? Should I call getProps method on abstract class inside my run method and then use it? Or just take it in the constructor and build it there? What is the difference and what is right way?

Источник

Abstract Class getter and setter usage

I have a question in regards to how I am planning to create my abstract models, I am using an abstract class as the base class and then subclasses, is it fine to use it like this? I did google and found some samples but none was exactly like how I am doing it.

public abstract class Vehicle
public class Truck extends Vehicle < String pickupBed; public setPickupBed(String pickupBed) < this.pickupBed = pickupBed; >public getPickupBed(String pickupBed) < return pickupBed; >public setType(String type) < this.type = type; >public getType(String type) < return type; >public setColor(String color) < this.color = color; >public getColor() < return color; >> 
public class Car extends Vehicle < public setType(String type) < this.type = type; >public getType(String type) < return type; >public setColor(String color) < this.color = color; >public getColor() < return color; >> 

I guess my question would be, should non abstract getters and setters be defined there? as I have them in the sub classes?

Yes, they should. Your base class is simply a data bag and it declares two fields: type and color . It is totally fine to declare those fields setters and getters in the base class only. Moreover, it’s even a preferred way for simple data bags + you can make those fields private as they usually should be (therefore, the Truck would only add 1 set/get method pair, and the Car class would be empty (empty classes are not that bad in many cases)).

4) non-abstract methods can have additional code that might do something more than just referencing fields (logging, validating, whatever you’d like them to do). These four points just come to my mind now, but there are more downsides. In general, abstract methods should only exist when it is not possible to define the behavior for that type (abstract class or interface), but subclasses can do that.

3 Answers 3

You need to create abstract getter and setter only if you need change behaviour of getiin and setting for your variables. If all child classes use the same getter and setter realization — you need to create getters and setters in the abstract class:

 public abstract class Vehicle < protected String type; protected String color; public String getType()< return type; >; public String setType(String type) < this.type = type; >. > 

In any case, if you need to include any logic for setter/getter in the future — you may override existing getter/setter:

public class Car extends Vehicle < public setType(String type)< if (type.equals("type1"))< this.type = type + "_1"; >else < this.type = type + "_2"; >> public String getType(String type)< return ""; > > 

You need to add abstract methods only if you want to force class-child implement some logic, f.e:

 public abstract class Vehicle < protected String type; protected String color; public String getType()< return type; >; public String setType(String type) < this.type = type; >public String getTypeDescription() < return "Type description: " + generateDescription(); >protected abstract String generateTypeDescription(); . > public class Car extends Vehicle < String generateTypeDescription()< return "foobar"; >> 

Источник

Abstract class getters and setters in java

So, to explain my code -> I have an abstract class of type Employee, it has its own fields, such as names. I then have the classes Admin, Sales and Manager that extend from Employee. these each have their own fields, such as fixedBonus for admin, percentBonus for Sales and an arraylist of employees for manager. I then have a driver class which contains an ArrayList of Employees, so it contains Admins, Sales and Managers. My problem arises with the Arraylist elements. Say I get an employee of class Admin from the ArrayList and try to get to their fixedBonus field with the getter getFixedBonus(), I simply cant. How can I make it so I can use the class specific getters and setters, not just the inherited ones? Here is a copy of my code, where the problem is arising. To be specific the problem is in case 5 and 6 of the switch statement.

private Employee editAnEmployee(Employee emp) < boolean exit = false; boolean validChoice = false; int choice = 0; Boolean sure = false; // used in the switch statement String newName; double newValue; Employee admin = new AdminWorker("0", "0", 0, 0, 0); // these are used Employee sales = new SalesWorker("0", "0", 0, 0, 0, 0); // to check the Employee manager = new Manager("0", "0", 0, 0); // class of the // employee // being sent // in, to edit // the fields // the employee // may hold do < do < validChoice = true; emp.toString(); StdOut.println("Which field would you like to edit?"); StdOut.println("1) First Name."); StdOut.println("2) last Name."); StdOut.println("3) Hourly rate."); StdOut.println("4) Hours worked in the last week."); if (emp.getClass().equals(admin)) < StdOut.println("5) Fixed Bonus."); >else if (emp.getClass().equals(sales)) < StdOut.println("5) Percentage bonus on sales."); StdOut.println("6) Value of sales made in the last week."); >else if (emp.getClass().equals(manager)) < StdOut.println("5) Department."); >StdOut.println("0) Exit."); choice = StdIn.readInt(); if (choice < 0 || choice >4) < if (emp.getClass().equals(admin) && choice else if (emp.getClass().equals(sales) && choice else if (emp.getClass().equals(manager)) < validChoice = true; >else < StdOut.println("You entered an invalid number! Try Again. "); validChoice = false; >> > while (!validChoice); switch (choice) < case 0: StdOut.println("You are now exiting. "); exit = true; break; case 1: StdOut.println("The employees first name is: " + emp.getFirstName() + ". What would you like the first name to be now?"); newName = StdIn.readString(); StdOut.println("Are you sure you want to change " + emp.getFirstName() + " to " + newName +"?(y/n)"); sure = ynChoice(); if(sure) emp.setFirstName(newName); break; case 2: StdOut.println("The employees last name is: " + emp.getLastName() + ". What would you like the last name to be now?"); newName = StdIn.readString(); StdOut.println("Are you sure you want to change " + emp.getLastName() + " to " + newName +"?(y/n)"); sure = ynChoice(); if(sure) emp.setLastName(newName); break; case 3: StdOut.println("The employees hourly rate is: " + emp.getHourlyRate() + ". What would you like the hourly rate to be now?"); newValue = StdIn.readDouble(); StdOut.println("Are you sure you want to change " + emp.getHourlyRate() + " to " + newValue +"?(y/n)"); sure = ynChoice(); if(sure) emp.setHourlyRate(newValue); break; case 4: StdOut.println("The employee has worked: " + emp.getHoursWorked() + " hours in the last week. What would you like that to be now?"); newValue = StdIn.readDouble(); StdOut.println("Are you sure you want to change " + emp.getHoursWorked() + " to " + newValue +"?(y/n)"); sure = ynChoice(); if(sure) emp.setHoursWorked(newValue); break; case 5: if (emp.getClass().equals(admin)) < StdOut.println("The employees fixed bonus is: " + emp.getFixedBonus() + ". What would you like that to be now?"); newValue = StdIn.readDouble(); StdOut.println("Are you sure you want to change " + emp.getFixedBonus() + " to " + newValue +"?(y/n)"); sure = ynChoice(); if(sure) emp.setHoursWorked(newValue); >else if (emp.getClass().equals(sales)) < StdOut.println("The employees percentage bonus is: " + emp.getPercentageBonus() + ". What would you like that to be now?"); newValue = StdIn.readDouble(); StdOut.println("Are you sure you want to change " + emp.getPercentageBonus() + " to " + newValue +"?(y/n)"); sure = ynChoice(); if(sure) emp.setHoursWorked(newValue); >else if (emp.getClass().equals(manager)) < StdOut.println("The employees fixed bonus is: " + emp.getFixedBonus() + ". What would you like that to be now?"); newValue = StdIn.readDouble(); StdOut.println("Are you sure you want to change " + emp.getFixedBonus() + " to " + newValue +"?(y/n)"); sure = ynChoice(); if(sure) emp.setHoursWorked(newValue); >break; case 6: StdOut.println("The employees sales in the last week are: " + emp.getLastWeeksSales() + ". What would you like that to be now?"); newValue = StdIn.readDouble(); StdOut.println("Are you sure you want to change " + emp.getLastWeeksSales() + " to " + newValue +"?(y/n)"); sure = ynChoice(); if(sure) emp.setHoursWorked(newValue); break; > > while (!exit); return emp; > 

Couldn’t you just make the abstract Employee class have abstract getter methods? That way, classes extending the Employee class will have to define their own getter behavior.

Источник

Can we put getters and setters in abstract classes.

@W M — It is just lazy to ask something like that instead of trying. You have a compiler — if you want to know if something like this is possible, try it. The compiler will complain if it is not valid. If will be faster for you and you will learn something in the process.

2 Answers 2

public abstract class ClassName < private String field; public String getString() < return field; >public void setString(String field) < this.field = field; >> 

More extended answer (I’m not sure that it’s actual for you right now):

You should realize that these methods (if they are not declared with final modifier) can be overriden in subclasses. That’s why it’s important to think about methods contracts and document them carefully. If one of the methods of your abstract class invokes another its method then this fact should also be documented.

All protected and public methods (and constants, and in very very seldom cases — protected fields) of your abstract class become a part of your API. Thus, other developers can use them and it’s not very easy to change them.

1) Think twice before making your class Serializable — this will make all subclasses searializable too and (if you want to produce not potentially broken program) you should care about possible serialization of any of the subclasses.

2) The same is actual for implementing Cloneable (do not better implement it in a top-level abstract class).

3) You should provide correct equals and hashCode implementation taking into account that 2 subclasses can be compared with your implementation from the abstract class.

4) Think about providing natural ordering (i.e. implementing Comparable interface). It’s often a good idea if there is a real natural ordering exists.

Источник

Читайте также:  Php удалить управляющие символы
Оцените статью