I have an assignment about doctors and prescriptions. In one of the classes I am not supposed to use int reit in the constructor (a sub class), as the super class have. The hint in the assignment is that int reit should always start on 3 when the prescription is made (how many times one can use the prescription). How am I supposed to change it from int reit to 3 (as I understood from a hint from an instructor in class).
Everythings in norwegian because we have to, hope that's okay.
Thanks for any help!
Here is the first class:
public abstract class Resept {
protected int id = 0;
protected static int teller = 1;
protected int pasientID = 0;
protected int reit = 0;
protected Legemiddel legemiddel;
protected Lege utskrivendeLege;
public Resept(Legemiddel legemiddel, Lege utskrivendeLege, int pasientID, int reit) {
this.legemiddel = legemiddel;
this.utskrivendeLege = utskrivendeLege;
this.id = teller;
this.reit = reit;
this.pasientID = pasientID;
}
}
Here is the next:
public class HvitResept extends Resept {
public HvitResept(Legemiddel legemiddel, Lege utskrivendeLege, int pasientID, int reit) {
super(legemiddel, utskrivendeLege, pasientID, reit);
}
}
And in this next class we're not supposed to write int reit in the constructor. Reit is always 3 with a new P-resept (birth control prescription).
public class PResept extends HvitResept {
public PResept(Legemiddel legemiddel, Lege utskrivendeLege, int pasientID, **int reit**) {
super(legemiddel, utskrivendeLege, pasientID, reit);
}
}
public class PResept extends HvitResept {
public PResept(Legemiddel legemiddel, Lege utskrivendeLege, int pasientID) {
super(legemiddel, utskrivendeLege, pasientID, 3);
}
}
You can call super(...);with the values you desire. super will call the constructor of its parent class.
public class PResept extends HvitResept {
private static final int reit = 3;
public PResept(Legemiddel legemiddel, Lege utskrivendeLege, int pasientID) {
super(legemiddel, utskrivendeLege, pasientID, reit);
}
}
Declaring this variable as private static and final will not occupy every time when we create new object of type PResept and also the value can't be changed due to final.
Related
I'm trying to create some methods for my object but the outside of the constructor, the object isn't recognized by it's name
public class Playlist extends SongRecord {
final int maxSongs = 50;
public Playlist() {
SongRecord[] list = new SongRecord[maxSongs];
}
public int size(){
return list.length();
}
}
The error message says list isn't recognized
Because your list scope is in the constructor if u want to access list every where u need to move your list to class scope
public class Playlist extends SongRecord {
final int maxSongs = 50;
SongRecord[] list;
public Playlist() {
list = new SongRecord[maxSongs];
}
public int size(){
return list.length();
}
}
Just move list to class scope:
public class Playlist extends SongRecord {
final int maxSongs = 50;
private SongRecord[] list;
public Playlist() {
list = new SongRecord[maxSongs];
}
public int size(){
return list.length();
}
}
this is the qa:
Define a class called MoreSpeed which extends the following class, and which provides a new method called incSpeed() which adds 1 to the inherited variable length.
this is my answer:
public class Speed {
private int length = 0;
public int getSpeed () { return length; }
public void setSpeed (int i) {
if (i > 0) {
length = i;
}
}
}
public class MoreSpeed extends Speed {
private int length;
public int incSpeed() {
return length+1;
}}
its says that the syntax is good but the class operation is wrong.
please help me,thanks.
No. You are shadowing the length from Speed. Instead, implement incSpeed with getSpeed() like
public int incSpeed() {
return getSpeed() + 1;
}
If you are supposed to modify it as well then use setSpeed(int) to do so
public int incSpeed() {
int s = getSpeed() + 1;
setSpeed(s);
return s;
}
I'm writing a program that is based around registering the amount of energy consumption that is being used by appliances within a house. So far, I have created various meter classes such as WaterMeter, GasMeter etc. with empty methods that need to be filed with values, I have also created classes for appliances that have methods that will be used to register the consumption of energy within each appliance. What I am working on now is applying the energy values that are stored within a constructor, putting those values into a timePasses() method that will then return those values to their specific meter's methods so that they can be registered. This is what I have so far:
Appliance class example:
public class ElectricShower extends Shower
{
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int x = -1;
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() { return instance; }
#Override
public int currentState()
{
if (x == 0)
return isOff;
else
{
return isOn;
}
//returns isOn;
}
#Override
public void useTime(int defaultTime)
{
defaultTime = 15;
incrementTime = 1;
}
public void shower()
{
//call timePasses() method
}
#Override
public int timePasses()
{
if(x == isOff)
return 0;
else
{
ElectricMeter.getInstance().incrementConsumed(electricityUse);
}
}
ElectricShower(int electricityUse, int gasUse, int waterUse, int timeOn)
{
super(electricityUse, gasUse, waterUse, timeOn);
this.electricityUse = 12 * incrementTime;
this.gasUse = 0 * incrementTime;
this.waterUse = 4 * incrementTime;
this.timeOn = 15 * incrementTime;
}
}
Meter example:
public class ElectricMeter
{
public int incrementConsumed(int value)
{
}
public int incrementGenerated()
{
}
public boolean canGenerate()
{
}
public String getConsumed()
{
}
public String getGenerated()
{
}
}
What I need to do next is:
take the values of electricityUse and waterUse and store them within the timePasses() else staement
Within the timePasses() else statement, place the value of electrcityUse in the incrementGenerated() method within the ElectricMeter class and do the same for the waterUse variable.
UPDATE
Classes have been updated, still struggling to find out how to make it work.
First of all, I assume you have an Appliance class that all the appliances extends from. You should create variables in the Appliance class that stores electricity, gas and water usage:
public class Appliance
{
public int electricityUse, gasUse, waterUse, timeOn;
// ...
}
Note that you should always use getters and setters instead of public fields. I'm just lazy :D
Change your constructor so that the variables above get set:
ElectricShower(int electricityUse, int gasUse, int waterUse, int timeOn)
{
super(electricityUse, gasUse, waterUse, timeOn);
// I don't know why you multiply the constant by incrementTime here. Seems weird. I think you can remove them.
this.electricityUse = 12 * incrementTime;
this.gasUse = 0 * incrementTime;
this.waterUse = 4 * incrementTime;
this.timeOn = 15 * incrementTime;
}
One way to write the else clause is to use the "Singleton Pattern".
In every meter class, write something like this:
private ElectricMeter() {}
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() { return instance; }
In the incrementConsumed method, you should accept a parameter that indicates how much to increment:
public int incrementConsumed(int value)
{
// logic here...
}
In the else clause, you can just do:
ElectricMeter.getInstance().incrementConsumed(electricityUse);
GasMeter.getInstance().incrementConsumed(gasUse);
WaterMeter.getInstance().incrementConsumed(waterUse);
You should review your design.
If you need to access to a class parameter you could just define it public or better create a so called getter method that returns the value.
Example:
public class MyData {
public int counter;
}
....
// Some other class
MyData data = new MyData();
data.counter = 5;
System.out.println(data.counter);
Or
public class MyData {
private int counter;
public void setCounter(int counter) {
this.counter = counter;
}
public int getCounter() {
return this.counter;
}
}
....
// Some other class
MyData data = new MyData();
data.setCounter(5);
System.out.println(data.getCounter());
In your code I see:
public int incrementConsumed()
{
//Store value of electricityUse.
}
But this method should just return an integer and have not parameter to get an input to store.
It should be:
public void incrementConsumed(int amount) {
this.amount += amount;
}
I'm concerned about this line:
gasUse = 0 * incrementTime;
If you multiply something to 0 it will be always 0...
I have several class (Sub1, Sub2, Sub3) that inherit all from an abstract class (Abs). All the Sub classes have several properties (size, delay, etc.) that are the same for all instances (like a static attribute). I would like to regroup all these subclasses attributes (and accessors) to avoid duplication of code and initialize it from only one place. Is it possible?
Here is a sample of code that show what I am forced to do to obtain the desired behavior:
public abstract class Abs {
protected static final int DEFALUT_SIZE = 1000;
protected static final int DEFALUT_DELAY = 1000;
}
class Sub1 extends Abs {
private static int size;
private static int delay;
public Sub1() {
size = DEFALUT_SIZE;
delay = DEFALUT_DELAY;
}
public void setSize(int size) { this.size = size; }
public int getSize() { return size; }
public void setDelay(int delay) { this.delay = delay; }
public int getDelay() { return delay; }
}
class Sub2 extends Abs {
private static int size;
private static int delay;
public Sub1() {
size = DEFALUT_SIZE;
delay = DEFALUT_DELAY;
}
public void setSize(int size) { this.size = size; }
public int getSize() { return size; }
public void setDelay(int delay) { this.delay = delay; }
public int getDelay() { return delay; }
}
class Sub3 extends Abs {
/* Same code here */
}
I would like to do the following:
Sub1 sub1 = new Sub1();
int size = Sub1.getSize(); // size == 1000
Sub1.setSize(500);
Sub2.setSize(700);
size = sub1.getSize(); // size == 500
size = Sub1.getSize(); // size == 500
size = Sub2.getSize(); // size == 700
With this solution, I am forced to rewrite all the same code in each subclasses.
I learned that the static attributes were not inherited, so impossible to do so from the abstract class...
It's generally a good idea to assume that, in all cases except constants, the keyword static is evil and should be avoided at all costs.
If you removed the static keyword from in front of size and delay, made them protected, and moved them into the abstract Abs class along with the initialisation code to set their initial values and the accessors and mutators (getters and setters), then you'd be able to remove their declarations and initialisation from the subclasses.
Your code should look something like this:
public abstract class Abs {
private static final int DEFALUT_SIZE = 1000;
private static final int DEFALUT_DELAY = 1000;
private int size = DEFAULT_SIZE;
private int delay = DEFAULT_DELAY;
public void setSize(int size) { this.size = size; }
public int getSize() { return size; }
public void setDelay(int delay) { this.delay = delay; }
public int getDelay() { return delay; }
}
Then anything that extends the Abs class will have these properties.
To share these properties between objects you'll have to do something a little different though, but there are many options. You can have a common class that holds the shared values that is injected into each instance at creation, or you can use some sort of eventing/observer pattern. However, this is quite an odd thing to want in the first place. Typically we'd have some sort of central object representing this information and just pass that around as needed -- you wouldn't typically have setters and getters on subclasses to implement this. What you have is akin to a service managing global properties.
I have a class named LotteryTicket that have 3 subclasses: Pick4, Pick5, and Pick6. I want to be able to call a method public void pickNumbers()where once called, will be able to recognize which LotteryTicket subclass is being used and ask for the appropriate amount of arguments (i.e. calling pickNumbers() in an instance of Pick5 will ask for 5 ints).
I've attempted to get around this by providing public void pick4Numbers(int firstPick, int secondPick, int thirdPick, int fourthPick) for 4, 5, and 6 in the LotteryTicket class, and having the pickNumbers() method call the appropriate method (which will get overridden) based on a field pickAmount. Unfortunately, this would entail having to provide arguments.
Here is the LotteryTicket class:
public class LotteryTicket
{
protected int pickAmount;
protected boolean isRandom;
protected ArrayList<Integer> numbersPicked;
protected Date datePurchased;
protected SimpleDateFormat sdf;
public LotteryTicket(int pickAmount, boolean isRandom)
{
// INITIALIZATION OF VARIABLES
this.pickAmount = pickAmount;
this.isRandom = isRandom;
// CONSTRUCTION OF ARRAYLIST
numbersPicked = new ArrayList(pickAmount);
}
/**
* The number pick method for ALL subclasses. Running this method will run the appropriate pickxNumbers
* method, where x is the pickAmount.
*
*/
public void pickNumbers()
{
if(pickAmount == 4){
pick4Numbers(int firstPick, int secondPick, int thirdPick, int fourthPick)
}
if(pickAmount == 5){
pick5Numbers(int firstPick, int secondPick, int thirdPick, int fourthPick, int fifthPick)
}
if(pickAmount == 6){
pick6Numbers(int firstPick, int secondPick, int thirdPick, int fourthPick, int fifthPick, int sixthPick)
}
}
/**
* The number pick method for the Pick4 subclass.
*
*/
public void pick4Numbers(int firstPick, int secondPick, int thirdPick, int fourthPick)
{
}
Pick4 class:
public class Pick4 extends LotteryTicket
{
/**
* Constructor for objects of class Pick4
*/
public Pick4(boolean isRandom)
{
super(4, isRandom);
}
/**
* Overloaded pick4Numbers() method. Depending on the ticket type, the amount of picks will vary.
* For example, Pick4 tickets will only ask for 4 int values, Pick5 tickets will ask for 5, etc.
*
*#param int firstPick
*#param int secondPick
*#param int thirdPick
*#param int fourthPick
*/
public void pick4Numbers(int firstPick, int secondPick, int thirdPick, int fourthPick)
{
numbersPicked.add(new Integer(firstPick));
numbersPicked.add(new Integer(secondPick));
numbersPicked.add(new Integer(thirdPick));
numbersPicked.add(new Integer(fourthPick));
}
In my opinion it would be better to do like this:
public class LotteryTicket {
protected int pickAmount;
protected boolean isRandom;
protected List<Integer> numbersPicked;
protected Date datePurchased;
protected SimpleDateFormat sdf;
protected int[] numbersToPick;
//To create random valued ticket
public LotteryTicket(int pickAmount) {
this.pickAmount = pickAmount;
isRandom = true;
}
//To create specified valued ticket
public LotteryTicket(int... numbersToPick) {
pickAmount = numbersToPick.length;
isRandom = false;
this.numbersToPick = numbersToPick;
}
public void pickNumbers() {
numbersPicked = new ArrayList<>(pickAmount);
if (isRandom) {
Random random = new Random(System.currentTimeMillis());
for (int i = 0; i < pickAmount; i++) {
numbersPicked.add(random.nextInt());
}
} else {
for (int i = 0; i < pickAmount; i++) {
numbersPicked.add(numbersToPick[i]);
}
}
}
}
And Pick4, Pick5 ... etc will be like this:
public class Pick4 extends LotteryTicket {
//For random valued ticket
public Pick4() {
super(4);
}
//For specified valued ticket
public Pick4(int pick1, int pick2, int pick3, int pick4) {
super(pick1, pick2, pick3, pick4);
}
}
If you want to extend from LotteryTicket, make pickNumbers() method abstract and accepting List or varargs:
public abstract class LotteryTicket {
//...
abstract public void pickNumbers(int... numbers);
//...
}
then in implementation classes, e. g. Pick4:
public class Pick4 extends LotteryTicket {
//...
#Override
public void pickNumbers(int... numbers) {
if (numbers.length != 4)
throw IllegalArgumentException("For Pick4, there must be exactly 4 numbers!");
for (int n : numbers) {
numbersPicked.add(n); // no need in explicit boxing, Java will do it for you
}
}
}