How to inherit specific instance variables in java - java

I want to inherit specific instances from a superclass, not all of them.
For example:
public class Snake extends Reptile {
private boolean hasLegs = false;
public Snake(double[] legLength, double tailLength, String color, boolean hasScales, boolean hasLegs) {
super(legLength, tailLength, color, hasScales);
this.hasLegs = hasLegs;
}
I want to inherit all instance variables from the class Reptile except double[] legLength(as snakes doesn't have legs).
How can I do that without changing code in the Reptile class?
Thanks.

I think you are asking how to not have to pass all the parameters you don't need to the parent class. You can't do that, you need to pass them all, but that doesn't mean you have to expose them all in the child class:
public Snake(double tailLength, String color, boolean hasScales) {
super(null, tailLength, color, hasScales);
this.hasLegs = false;
}
You can't just get some variables from the parent - you get them all. You can set them to values that make sense for your subclass. That is the whole point!

Related

How to keep the same value of a field for multiple calls to a Class

I'm running into a problem that I can't solve basically, I'm trying to build a code for a house and I wanna make multiple calls to the house without having to turn on the light every single time
My field value
private boolean turnon = false;
and then my method to turn on the the lights
public void turnon() {
turnon = true;
}
Basically what I want to avoid is to not call the method every single time I wanna add a new House, basically once I turn it on it turns on for every instance of the class.
House x = new House();
x.turnon();
So let's say I create another class of House
House y = new House();
I want the lights to be turned on in y since I've already turned them on in x
I tried defining the method statically but it didn't work, any suggestions would be appreciated
In your House class, add this:
public House() {
turnon();
}
I figured out the OP wants to have the first one's lights not turn on, so you can make a constructor with an argument of boolean called "lightsOn" and if true, it will turn on the lights, and if false, will not.
public house(boolean lightsOn) {
if (lightsOn) {
turnon();
}
}
Alternatively, you can simply add another constructor with an argument and only call that constructor on the first instance of "House"
public House() {
turnon();
}
// Only for the first house
public House(boolean lightsOff) {
turnon = false;
}
Whenever you are creating a new house, you can initialize the value of field turnOn(notice the camelcase convention ) in the constructor.
public House(boolean turnOn) {
// initializing other fields
this.turnOn = turnOn;
}
Then you can provide regular getter and setter to access the turnOn field.
When creating other houses , you can simply use your no-arg constructor.
public House() {
// initializing other fields
}
The fundamental reason for the confusion here is:
'House' and a light 'Switch' don't belong to the same class!
So I think you should model House and a Switch as different classes.
And just make the house object 'aggregate' a set of 'Switches' and other objects in the house.
Eg:
class House {
List<ElectricalFitting> devices;
}
class Switch extends ElectricalFitting {
...
}
You can extract a default state for the light as static field into a base class.
Your House class extends this base class, inhertites the default state field and copies in it's constructer the default to the instance state. The two setters change both, the default and instance state.
If for example the default state is light off (false), every new instance of House has it's light turned off.
But if you turn the light on (true) in one house than the default change to true and every new instance has the light turned on.
Every existing instance of House acts independenly to all other houses on turning light on or off.
public abstract class HouseBase {
protectet static boolean defaultSwitchState = false;
}
public class House extends HouseBase {
private boolean turnOn = false;
public House() {
turnOn = defaultSwitchState;
}
public void turnOn() {
super.defaultSwitchState = true;
turnOn = true;
}
public void turnOff() {
super.defaultSwitchState = false;
turnOn = false;
}
}

Wish to initialize member before passing to parent constructor

Here is a toy example of my conundrum:
public abstract class Car {
public Car(Seat[] seatsParam) { // Could be protected.
driverSeat = new DriverSeat();
seats = new ArrayList<Seat>();
seats.add(driverSeat);
seats.addAll(seatsParam);
}
private final List<Seat> seats;
private final DriverSeat driverSeat;
}
public class MyCar extends Car {
public MyCar() {
super(new Seat[]{new PassengerSeat()}); // Cannot assign to member.
}
public PassengerSeat getPassengerSeat() { // Would like this accessor.
return passengerSeat;
}
private final PassengerSeat passengerSeat;
}
Car has a list of Seat (the seat supertype), ideally initialized in the constructor. Every car has a DriverSeat. MyCar also has a PassengerSeat which I would like to access from the subtype, but also from the parent list (as a Seat).
Some things that I have shot down:
The code above: passengerSeat won't be initialized in the subclass. I could get the list in MyCar's constructor and downcast, but this is ugly.
Making passengerSeat static: it shouldn't be static since there could be many other MyCars with unique seats.
Have Car define an abstract getSubclassSeats() to which it adds driverSeat: this won't work in the constructor since passengerSeat won't have been initialized. I could make seats non-final and do it after the constructor but, again, ugly.
I want to say this is something I should be able to express in OO, define a variable and pass it to the parent to reference. But I cannot think of how to do it nicely. It's been awhile since I worked with C++, but is this what initialization lists solve? If so, does Java have an equivalent?
I've seen people with similar problems use thread-local variables and god knows what other awful tricks, luckily there's an easy solution:
public MyCar() {
this(new PassengerSeat());
}
private MyCar(PassengerSeat seat) {
super(new PassengerSeat[]{seat});
// Well do something with your seat now.
}

Can I reasonably access a variable of an extending class?

I have an array of objects from one class that I made, which includes both objects of that type and objects that extend the first object. I want to access a variable that the extending object has that the first object does not, once I know that the object I am talking about is the extending one. A simplified example of this is shown below:
public class Parent {
public boolean isChild=false;
}
public class Child extends Parent {
public int i=5;
public Child() {
isChild=true;
}
}
public class main {
public static void main(String[] args) {
Parent x=new Child();
if (x.isChild) {
System.out.println(x.i); //this is what I want to do...
//... but I get an error because Parent doesn't have a variable called i.
}
}
}
So, is there any way for me to get around this? (I looked at making a protected static variable but that didn't seem to be what I wanted because I need multiple copies of it.)
Okay, as for how this is actually being used (which I incorrectly didn't include the first time) I am making my own computer programming language for fun. I have an ArrayList of objects that have been created, and allow users of this language to make their own objects as well as use ones that I have made with both java code and code in my language.
I make strings (aka child) in java and have them extend my wafl_object class (parent). This way they can be carried around in that ArrayList without me having to go around with a different array for every object I make. However, I want to accept a String as a parameter for a different class, and I cannot see its value because it is in an object array and I was treating it like an object. I have now fixed this problem by casting it as a String, once I know that it really is one, and then looking at its value. In this situation, it was easier to just cast it, but in others abstactness may have been more usefull.
Instead of testing the type of the object, use polymorphism:
public abstract class Parent {
public abstract int getValue();
}
public class Child extends Parent {
#Override
public int getValue() {
return 5;
}
}
public static void main(String[] args) {
Parent x = new Child();
System.out.println(x.getValue());
}
Just try something like :
if(x instanceof Child){
System.out.println(((Child)x).i);
}
First of all, isChild can be replaced by using instanceof instead: if (x instanceof Child). Afterwards, you can safely cast x to Child: Child childX = (Child)x. childX then gives you access to x.
Generally, checking for types is frowned upon. Normally you should design your functions such that they accept a type that is general enough to do everything they need to do without having to cast to deriving class types.
You don't need your isChild variable. You can use if (x instanceof Child). But in order to access i, you'll have to case x to Child.
In addition, don't access a member directly. Data members such as i should be private and you should access them by getters.
public class main {
public static void main(String[] args) {
Parent x=new Child();
if (x instanceof Child) {
System.out.println((Child)x.getI());
}
}
}
You can solve this with instanceof and a cast, as described in other answers, but in general it's better to use polymorphism, to define a method that subclasses can override. The exact way to do this will depend on the exact nature of your program, but here's one possibility, where I'm using Employee for Parent and HourlyEmployee for Child (constructors and other logic would need to be filled in):
public class Employee {
private String name;
public String getDescription() {
return name;
}
}
public class HourlyEmployee {
private int wage;
#Override
public String getDescription() {
return super.getDescription() + " [at $" + wage + " per hour]";
}
}
Then the class that uses an Employee wouldn't need to test whether it's an HourlyEmployee; it just calls getDescription, and the method either will or won't include the hourly wage in the result, depending on what class it is.
There's no reason to use parent or use child
public class main {
public static void main(String[] args) {
Parent x=new Child();
if (x.isChild) {
System.out.println(((Child)x).i); //this is what I want to do...
//... but I get an error because Parent doesn't have a variable called i.
}
}
}
First of all, previous answers are correct and around the same point. You MUST let the compiler know that the you want to use (x) as a child and not parent.
So, and sticking with your code sample, the answer is to modify the System.out statement to the following:
System.out.println(((Child)x).getValue());

How can I transform an object into a different object from the same base class?

Let's say I have a board game where players can buy the squares that they land on. I have a method in my abstract base class of Squares called this:
public abstract void applyLandOnAffect(Player player);
Then in my class of BuyableSquares I implement this method shown below:
#Override
public void applyLandOnAffect(Player player){
//Offer them the chance buy the square here.
}
Then if they choose to buy the square I want the object to change from a BuyableSquares() into a BoughtSquare(). The code in the BoughtSquare would handle what happens when another player lands on a bought square. But the issue is how and where I should transform it.
I was thinking this type of code:
this = new BoughtSquare();
But it's not accepted syntax.
How do I approach this?
Thanks
If you are using polymorphism to have different processing of Square instances depending on its type, my suggestion is to use State design pattern.
To introduce it in your application you should:
define a new interface named e.g. SquareState with methods that differ depending on the square type
public interface SquareState {
void applyLandOnAffect(Player player);
}
define all square types which will implement this interface and provide the implementation of the methods from the SquareState interface
public AvailableState implements SquareState {
public void applyLandOnAffect(Player player) { // ..
}
}
public BoughtState implements SquareState {
public void applyLandOnAffect(Player player) { // ..
}
}
introduce a new attribute inside the Square class that will store the current state of the square
public class Square {
private SquareState state;
// ..
}
Once you have done that, changing the state of the Square will be a matter of calling:
this.state = new BoughtSquare();
First of all, you can't assign anything to this.
In order to achieve what you want, why not create a flag in the BuyableSquares class, that indicates whether or not the square is bought.
public class BuyableSquares extends Squares {
private boolean bought = false; // by default
//...
public void markAsBought() {
bought = true;
}
}
Once you instantiate an object, you cannot change its class.
An option would that, as both classes already extend a superclass, use that as the reference to the classes so you can easily replace them. So, you store your board as a set (or list or array) of Square, each of them is a BuyableSquare or a BoughtSquare. When a BuyableSquare must be transformed, you replace it from your structure with the correspondent BoughtSquare (of course, a BoughtSquare constructor that takes the original BuyableSquare as a parameter would be advisable).
I agree with the previous post the the State pattern is best. Setup the Square class with a state variable that you can switch to different states when different events happen to that square. Then, have each state encapsulate the behaviors for what happens when a player lands on the square and it is in a particular state. To change states, just reassign a different instance of SquareState to the state variable. A very simple outline would look like this.
interface SquareState{
void applyLandOnAffect(Player player);
}
public class Square{
private SquareState state = new AvailabelState();
}
public AvailableState implements SquareState{
public void applyLandOnAffect(Player player){
...
}
}
public BoughtState implements SquareState{
public void applyLandOnAffect(Player player){
...
}
}
You should just have one class called Square instead of having separate classes for purchased squares and unpurchased squares. Or you can extend Square if you plan on having other types of squares that are not purchasable. Create a boolean value in your class called purchased that's set to false by default. Then when the square is purchased you can set the value to true.
public class PurchaseableSquare extends Square
{
private boolean purchased;
public Square()
{
this.purchased = false;
}
public void purchaseSquare()
{
this.purchased = true;
}
}
This is one of the examples that justify the rule prefer composition over inheritance.
In your case you have Square subtypes where you define the behavior. The problem is that your object can't change class, so it can't be transformed from BuyableSquare to BoughtSquare. A design based on composition would create a new interface for the square's state. So Square has a SquareState. The different behaviors of bought and not bought squares will be defined in different subtypes of the SquareState interface. So when somebody buys a square you just change its state. Something like:
public class Square {
private SquareState state = new Buyable();
public void buyMe() {
this.state=new Bought();
}
}

Call a child class method from a parent class object

I have the following classes
class Person {
private String name;
void getName(){...}}
class Student extends Person{
String class;
void getClass(){...}
}
class Teacher extends Person{
String experience;
void getExperience(){...}
}
This is just a simplified version of my actual schema. Initially I don't know the type of person that needs to be created, so the function that handles the creation of these objects takes the general Person object as a parameter.
void calculate(Person p){...}
Now I want to access the methods of the child classes using this parent class object. I also need to access parent class methods from time to time so I CANNOT MAKE IT ABSTRACT.
I guess I simplified too much in the above example, so here goes , this is the actual structure.
class Question {
// private attributes
:
private QuestionOption option;
// getters and setters for private attributes
:
public QuestionOption getOption(){...}
}
class QuestionOption{
....
}
class ChoiceQuestionOption extends QuestionOption{
private boolean allowMultiple;
public boolean getMultiple(){...}
}
class Survey{
void renderSurvey(Question q) {
/*
Depending on the type of question (choice, dropdwn or other, I have to render
the question on the UI. The class that calls this doesnt have compile time
knowledge of the type of question that is going to be rendered. Each question
type has its own rendering function. If this is for choice , I need to access
its functions using q.
*/
if(q.getOption().getMultiple())
{...}
}
}
The if statement says "cannot find getMultiple for QuestionOption." OuestionOption has many more child classes that have different types of methods that are not common among the children (getMultiple is not common among the children)
NOTE: Though this is possible, it is not at all recommended as it kind of destroys the reason for inheritance. The best way would be to restructure your application design so that there are NO parent to child dependencies. A parent should not ever need to know its children or their capabilities.
However.. you should be able to do it like:
void calculate(Person p) {
((Student)p).method();
}
a safe way would be:
void calculate(Person p) {
if(p instanceof Student) ((Student)p).method();
}
A parent class should not have knowledge of child classes. You can implement a method calculate() and override it in every subclass:
class Person {
String name;
void getName(){...}
void calculate();
}
and then
class Student extends Person{
String class;
void getClass(){...}
#Override
void calculate() {
// do something with a Student
}
}
and
class Teacher extends Person{
String experience;
void getExperience(){...}
#Override
void calculate() {
// do something with a Teacher
}
}
By the way. Your statement about abstract classes is confusing. You can call methods defined in an abstract class, but of course only of instances of subclasses.
In your example you can make Person abstract and the use getName() on instanced of Student and Teacher.
Many of the answers here are suggesting implementing variant types using "Classical Object-Oriented Decomposition". That is, anything which might be needed on one of the variants has to be declared at the base of the hierarchy. I submit that this is a type-safe, but often very bad, approach. You either end up exposing all internal properties of all the different variants (most of which are "invalid" for each particular variant) or you end up cluttering the API of the hierarchy with tons of procedural methods (which means you have to recompile every time a new procedure is dreamed up).
I hesitate to do this, but here is a shameless plug for a blog post I wrote that outlines about 8 ways to do variant types in Java. They all suck, because Java sucks at variant types. So far the only JVM language that gets it right is Scala.
http://jazzjuice.blogspot.com/2010/10/6-things-i-hate-about-java-or-scala-is.html
The Scala creators actually wrote a paper about three of the eight ways. If I can track it down, I'll update this answer with a link.
UPDATE: found it here.
Why don't you just write an empty method in Person and override it in the children classes? And call it, when it needs to be:
void caluculate(Person p){
p.dotheCalculate();
}
This would mean you have to have the same method in both children classes, but i don't see why this would be a problem at all.
I had the same situation and I found a way around with a bit of engineering as follows - -
You have to have your method in parent class without any parameter and use - -
Class<? extends Person> cl = this.getClass(); // inside parent class
Now, with 'cl' you can access all child class fields with their name and initialized values by using - -
cl.getDeclaredFields(); cl.getField("myfield"); // and many more
In this situation your 'this' pointer will reference your child class object if you are calling parent method through your child class object.
Another thing you might need to use is Object obj = cl.newInstance();
Let me know if still you got stucked somewhere.
class Car extends Vehicle {
protected int numberOfSeats = 1;
public int getNumberOfSeats() {
return this.numberOfSeats;
}
public void printNumberOfSeats() {
// return this.numberOfSeats;
System.out.println(numberOfSeats);
}
}
//Parent class
class Vehicle {
protected String licensePlate = null;
public void setLicensePlate(String license) {
this.licensePlate = license;
System.out.println(licensePlate);
}
public static void main(String []args) {
Vehicle c = new Vehicle();
c.setLicensePlate("LASKF12341");
//Used downcasting to call the child method from the parent class.
//Downcasting = It’s the casting from a superclass to a subclass.
Vehicle d = new Car();
((Car) d).printNumberOfSeats();
}
}
One possible solution can be
class Survey{
void renderSurvey(Question q) {
/*
Depending on the type of question (choice, dropdwn or other, I have to render
the question on the UI. The class that calls this doesnt have compile time
knowledge of the type of question that is going to be rendered. Each question
type has its own rendering function. If this is for choice , I need to access
its functions using q.
*/
if(q.getOption() instanceof ChoiceQuestionOption)
{
ChoiceQuestionOption choiceQuestion = (ChoiceQuestionOption)q.getOption();
boolean result = choiceQuestion.getMultiple();
//do something with result......
}
}
}

Categories

Resources