I have an abstract class like this:
public abstract class Block {
private boolean collided = false;
public boolean hasCollided() {
return collided;
}
public void markCollided() {
collided = true;
}
}
I have 4 sub classes for the Block class. Those class also require to receive the collided variable. That means the two methods should be overridden by the 4 sub classes of Block. How can I make it work?
If I try to override it, it will show error because sub classes does not contain such a variable in it.
How can I receive the collided variable in all sub classes?
Also,I created an array of block class that array contains 4 subclass objects.Is it possible to set different values for the collided variable for each object,while traversing the array?
In short,the colllided variable can be unique for each object in the array?
You need to use the public methods hasCollided(), markCollided() etc., because collided is a private variables for class Block .
The fact the 4 sub classes extends Block ,that doesn't mean can access private fields. Block provided public hasCollided,markCollided to access its private variables.
You cannot access the collided variable directly because it is private. But
you can use the hasCollided() method of the superclass to return the parent class' collided variable.
public class subBlock {
public boolean hasCollided() {
return super.hasCollided();
}
public void markCollided() {
super.hasCollided()= true;
}
}
Related
So as part of a car rental system I need to write classes to represent large and small cars, the difference between these being that they have different size tanks and consume fuel at different rates. Currently my approach is to have an interface, Car, implemented by an abstract class AbstractCar, which is extended by two concrete classes SmallCar and LargeCar. However this is my first time using interfaces and abstract classes (we are just covering them in class and this assignment is designed to assess our knowledge of them) and I'm having trouble knowing what to place in what class.
The fill method implementations are exactly the same, they just need to refer to the correct value of FUEL_CAPACITY, so it feels that I should be implementing these methods in the AbstractCar class, but then I don't know how to get them to refer to the correct FUEL_CAPACITY values. The field fuelLevel is also obviously held by all cars so it feels that I should declare it in AbstractCar, but then I cannot access it from the subclasses without removing its privacy.
Would anyone be able to help me figure out what I'm doing wrong or misunderstanding about interfaces and inheritance? One thing I've been considering is producing an enum CarType, having AbstractCar hold a CarType as a field and all implementation is done in the AbstractCar class using if statements to switch to the correct FUEL_CAPACITY value, and simply using SmallCar and LargeCar as constructors or factory classes without much or even any actual implementations.
Thanks in advance for any help I realise its a bit long winded, however I try to make sure I'm fully understanding the concepts we are learning and that I'm implementing them correctly rather than just botching together something that 'works' but might not necessarily be the correct or most elegant solution.
You can transfer the logic to the AbstractCar with the values like you pointed out. Then just set those values in the constructor of SmallCar and LargeCar. This would be one approach. Like you pointed out, you always have to have the common logic in the parent class. You want to avoid duplicate code. Then you just have to make sure you set different values in the constructor. And if you know the fix value (as you do from the given example), you can even omit giving parameters to SmallCar or LargeCar constructors and just set those fixed values in the super() call inside the constructor.
Here is the implementation of my solution.
The interface Car, where I REMOVED the getFuelMethod() method since the access level has to be protected:
public interface Car {
RegistrationNumber getRegistration();
int getFuelCapacity();
// int getFuelLevel(); this can not be implemented
// all methods in an interface are PUBLIC
// so you have to lower the access level by removing it from the interface
// HERE goes the rest of the method signatures
}
}
The abstract class AbstractCar:
public abstract class AbstractCar implements Car {
// this is the common variable
// that is why we save it in the parent class
private int fuelCapacity;
private int fuelLevel;
// we forward the value to the parent constructor with the super call
public AbstractCar(int fuelCapacity) {
this.fuelCapacity = fuelCapacity;
// I set the value to 0 for the start, but
// you can also pass the value to the super call,
// same as fuelCapacity - it is up to you
this.fuelLevel = 0;
}
// The getters and setter allow us to retrieve the values
// from the abstract class through capsulation!
// here we have the getter to be able to retrieve the value from SmallCar and LargeCar
public int getFuelCapacity() {
return.fuelCapacity;
}
public void setFuelCapacity(int fuelCapacity) {
this.fuelCapacity = fuelCapacity;
}
protected int getFuelLevel() {
return fuelLevel;
}
protected void setFuelLevel(int fuelLevel) {
this.fuelLevel = fuelLevel;
}
// HERE goes the rest of the code
}
Here is the SmallCar implementation:
public class SmallCar extends AbstractCar {
private static final int FUEL_CAPACITY = 45;
public SmallCar() {
// we set the value in the parent class
super(FUEL_CAPACITY);
}
public int drive() {
// HERE goes the logic for drive for SmallCar. Same method is needed
// in the LargeCar class, because the logic differes.
}
// HERE goes the rest of the code
}
If you just want to hide FUEL_CAPACITY from the class user but not from the further developers, you can declare it as protected in the AbstractCar and initiallize it with a proper value in the child classes. Also I would declare a getter method getCapacity() in the AbstractCar which returns this value.
If your Capacity is only one property (only data) of Car, use #Jernej K approach, but if calculating the capacity may have some logic, use this:
Best way is to use abstract methods. you put a method to abstract Integer getCapacity(); in your abstract class
public abstract class AbstractCar implements Car {
private final RegistrationNumber registration;
private boolean isRented;
AbstractCar() {
this.registration = RegistrationNumber.getInstance();
}
public RegistrationNumber getRegistration() {
return registration;
}
public boolean isRented() {
return isRented;
}
//You can use this method in other methods of AbstractCar, but is implemented in your concrete classes
public abstract Integer getCapacity();
public boolean isFull() {
if (fuelLevel == getCapacity()) {
return true;
} else return false;
}
}
and then use it in other functions. and in your concrete class, you define the body of method:
public Integer getCapacity(){
//Your logic to calculate capacity for every concrete class here
}
A friend of mine just brought up that I should use getters for classes, is this considered good practice or not? I couldn't find the answer elsewhere.
And how about Setters for classes? Does that even exist?
Thanks for your input.
public class Movement {
private Player p;
public Movement(Player p) {
this.player = p;
}
// methods
}
public class Player {
/**
* The movement class that handles all players movements
*/
private Movement movement;
public Player() {
this.movement = new Movement(this);
}
public Movement getMovement() {
return this.movement;
}
}
#people saying duplicate question
This is not simple variables that require protection by being private.
This is about the habit of adding a getter for a class, which I don't get since the class is already public.
And how about Setters for classes? Does that even exist?
AFAIK, not in Java. Whenever you want to modify class properties or behaviour, you change its members or methods respectively (by "setter" methods in some cases, yes), or you provide another constructor to a class to create some specified instance of it.
The point of getters and setters is to provide encapsulation concept, which is used, mainly, to restrict or configure access to some of the certain object's components (not the whole class instance itself).
As for classes, in Java we have access modifiers for the same reason.
My guess is that your friend may talk about something like Singleton pattern in which you're actually using some kind of "getter" method to get access to class instance like in here:
public class Singleton {
private static Singleton singleton = new Singleton( );
/* A private Constructor prevents any other
* class from instantiating.
*/
private Singleton(){ }
/* Static 'instance' method */
public static Singleton getInstance( ) { //That's what you are probably asking about
return singleton;
}
/* Other methods protected by singleton-ness */
protected static void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}
Or it's about static factory pattern given as example in this answer.
Summary: Despite the fact that the class itself is public, there's no public constructors availiable, so this is the reason to provide some kind of a "getter". So this is your case, I suppose.
Getter and setter are used to hide/protect private/protected variable from
other Classes. Exemple:
Class Person{
private String name;
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
I don't see any difference between setting a member variable versus setting a object. You can set the value for an object in same was as you set the member variables.
public void setPlayer(Player player){
this.player = player;
}
public Player getPlayer(){
return player;
}
public void setMovement(Movement movement){
this.movement = movement;
}
public Movement getMovement(){
return movement;
}
If you don't want to set the object value explicitly, you can set the value in constructor and provide only getter method to callers so that no one else can set the value except by calling constructor. Even if you do not want to call constructor for setting the value, create Singleton class by making constructor as private. I hope you know how to create Singleton classes
I have the following:
Public Abstract class Entity
protected int damagePoints = 0;
public getDamagePoints() {
return this.damagePoints;
}
Public abstract class IA extends Entity
Public class Zombie extends IA implements Attacker {
protected int damagePoints = 40;
}
Public class Engineer extends Entity implements DamageReceiver;
Public interface Attacker {
public attack(Entity entity);
}
Public interface DamageReceiver {
public receiveDamage(Attacker entity)
}
The Engineer class has this method overriden:
#Override
public void receiveDamage(Attacker entity) {
if (entity instanceof Zombie) {
int damagePoints = ((Zombie) entity).getDamagePoints();
this.setHealthPoints(this.getHealthPoints() - damagePoints);
}
}
Now I have an Engineer instantiated, and a Zombie.
When I do Zombie.attack(engineer), and I put a breakpoint in receiveDamage() in Engineer class, I get that damagePoints is 0.
Any clue of why this happens? Is this because I duplicated the property damagePoints? If so, how can I have a Zombie to have 40 of damage points without repeating the this.damagePoints = 40 in all constructors?
You re-declared damagePoints in Zombie, hoping that getDamagePoints() in Entity would pick up the new value in Zombie, but as you've seen, it didn't. In Java, polymorphism works with method calls, but not with variables. The damagePoints variable in Entity is the variable in scope for the getDamagePoints() method, so 0 is returned, from Entity's damagePoints variable.
To get 40 returned in Zombie, you don't need to re-declare another variable of the same name, hiding the damagePoints variable in Entity, but you can override the getDamagePoints() method in Zombie. You don't need a variable for that, much less a variable of the same name (unless you plan on having that quantity change during the game). In Zombie:
#Override
public int getDamagePoints() {
return 40;
}
You may even want your getDamagePoints() method to be abstract in Entity, forcing subclasses to implement the method. This would mean that the variable damagePoints would be unnecessary in Entity.
public abstract int getDamagePoints();
This is happening because when you call getDamagePoints, it's returning the abstract class Entity's damagePoints value, not the class that has extended it. Fix this by making Entity's getDamagePoints method abstract, and provide an implementation for every extended class.
It appears Zombie has multiple constructors, all of which need to initialize damagePoints to avoid repeated code, including possibly repeating the method getDamagePoints.
The solution is to use "this" to tie constructors together. For example, if one constructor takes a superset of the parameters for each of the other constructors, do the actual work in it:
public Zombie(/* some subset of parameters */){
this(/* full set of parameters with defaults filled in */);
}
public Zombie(/* full set of parameters */){
damagePoints = 40;
/* rest of initialization */
}
If there is no common superset constructor, you can still use "this" to do the common work. You may need to use a special private constructor:
private Zombie(boolean special) {
damagePoints = 40;
}
public Zombie() {
this(true);
/* Rest of the constructor */
}
I do not quite understand the use of "static" properly.
I have a class which includes variables that I want to access from a different class.
However, when I try to access this getter method from the different class I get an error stating:
"non-static method getAccNumber() cannot be referenced from a static context."
So, how can I find this variable's value without making it static. The problem with this is if I make it static, every instance of this object overwrites the previous value.
So they all end up with the same account number in this case.
Let me explain in more detail:
I have a Class called Account, which contains a variable called accountNumber, and a getter method called getAccNumber().
I have a second class called AccountList which is a separate arraylist class to store instances of Account. I want to create a method to remove an element based upon its accountNumber. So I'm searching and using getAccnumber() within the AccountList class to compare with a user parameter and removing if correct!
But I can't use this method without making it static!!
Any help/explanation would be greatly appreciated :)
This is what I am trying to do:
public boolean removeAccount(String AccountNumber)
{
for(int index = 0; index < accounts.size(); index++)
{
if (AccountNumber.equals(Account.getAccNumber()))
{
accounts.remove(index);
return true;
}
}
return false;
}
Thank you!
Let's take an example where you have
public class A {
static void sayHi() { System.out.println("Hi");
//Other stuff
}
and
public class B {
void sayHi() { System.out.println("Hi");
//Other stuff
}
Then
public class C {
public C() {
A.sayHi(); //Possible since function is static : no instantiation is needed.
B.sayHi(); //Impossible : you need to instantiate B class first
}
You can check out this link for a short definition:
Static Method Definition
If you declare a variable as static, it will not be unique for each instance of the class. If you declare the variable as private only, then you can create getter and setter methods that will allow you to access the variable after you have created an instance of the class. For example, if you have classA and classB and you are working in classB and want the private int size of classA:
classA a = new ClassA();
int size = a.getSize(); //getSize() returns the private int size of classA
A static variable is one that lives with the class itself. A non-static variable is unique to each instance of that class (i.e., each object built from that class.) A static variable you can access as a property of the class, like:
SomeclassIMadeUp.numberOfFish;
so if you change the numberOfFish property for that class, anywhere you reference it, you see the change (as you've noticed.)
To have one unique to each instance, don't declare the variable as static and then add a getter and/or setter method to access it.
like
private int numberOfFish;
public int getNumberOfFish() { return (numberOfFish); }
So to your question...
Ocean pacific = new Ocean();
pacific.water = Ocean.salty; // <-- Copying the value from a static variable in the class Ocean
// to the instance variable in the object pacific (which is of Ocean class).
pacific.setNumberOfFish(1000000000);
Octopus o = new Octopus();
o.diningOpportunities = pacific.getNumberOfFish(); // <-- Calls the public method to return a
// value from the instance variable in the object pacific.
I have the following code:
public static boolean isRelated(Animal first, Animal second){
boolean result=false;
if(first(parentA).equals(second(parentA)))
result=true;
return result;
}
basically, I need to be able to access the parent A instance variable that is in the Animal class from this static method.
I understand that, to access instance variables in a static method, you need to create an object but I already have 2 brought in.(Parent A and Parent B)
Could you guys tell me what the problem here is?
In order to access instance variable, you need to use an instance. You don't have to create it each time you need it, as long as you have one.
And for your code:
if(first.getParentA().equals(second.getParentA()))
In this case you need to make sure than first.getParentA() isn't null before comparing (or else you'll get NPE)
if(first(parentA).equals(second(parentA)))
basically, I need to be able to access the parent A instance variable that is in the Animal class from this static method.
That is not the correct syntax to access instance members
should be
if(first.parentA.equals(second.parentA))
More over use setters and getters to access the data such that
public class Animal {
private String parentA;
// code
public String getParentA() {
return parentA;
}
public void setParentA(String parentA) {
this.parentA = parentA;
}
}
}
Then use the line if(first.getParentA().equals(second.getParentA()))
Static methods are created in method area, and is the first to be created. Instance variables are created in heap after static methods are created. Hence, accessing instance variables directly is not possible. Always make use of an object to access such variables.