Java extend class with parameter

extending a class with an extra parameter

I now want to extend this class, not splitting the data into 2 different ints but into 3 different ints. So besides the 2 already exisiting integer vars I want one extra. Whats the easiest way of doing this? Your help is appreciated! Kind regards, Kipt Scriddy

I am not really used to this kind of programming, Id rather use another class but for this assignment I need to do it. I am a bit confused by the fact that even if I extend the class with another int. What happens to the previous 2 ints. Will they be callable in this class?

3 Answers 3

I think it would be better (and quite easy) the create more general class that will be able to deal with any number of years you pass to it:

public class Period < int[] years; Period() < >Period(String periode) < String[] periodeSplit = periode.split("-"); years = new int[periodeSplit.length]; for (int i = 0; i < periodeSplit.length; i++) < years[i] = Integer.parseInt(periodeSplit[i]); >> public String toString() < String result = ""; for (int i = 0; i < years.length; i++) < result += "Year " + i + ":" + years[i] + "\n"; >return result; > > 

If the original class really have to be extended than it can be done like this:

class ExtendedPeriod extends Period < int thirdPart; ExtendedPeriod(String periode) < String[] periodeSplit = periode.split("-"); this.firstYear = Integer.parseInt(periodeSplit[0]); this.secondYear = Integer.parseInt(periodeSplit[1]); this.thirdPart = Integer.parseInt(periodeSplit[1]); >public String toString() < return "Day: " + this.firstYear + "\n" + "Month: " + this.secondYear + "\nYear: " + this.thirdPart; >> 

I would recommand to change variable names ‘firstYear’ and ‘secondYear’ to something different, like ‘firstPart’, ‘secondPart’ because for extendedPeriod they aren’t years anymore (I left them in my code so it would compile with yours but called the new int ‘thirdPart’). I don’t feel that this is the best use of inheritance but if that’s what’s needed. I also wanted to reuse toString from Period like this:

but for it to have sense you would have to chagne toString method in Period not to call values ‘years’.

Источник

Extend a class + new parameter

in this 2nd class I will override my getAllMyStuffMethod, but inside this method I’ll need to use the newData parameter from the constructor:

private String getAllMyStuffMethod() < if (newData==0) // do something >

@AdamArold I used this quick names in order to quickly expose here the problem, but thanks for the comment

4 Answers 4

Just create a new field in the GetSecondStuff class and assign it in the constructor. Then you can use newData in the overriden method.

if I add private String newData; I can use it in the constructor only after the super(). And the function getAllMyStuff() is called from super() so, it doesn’t help :e 🙁 or i missunderstood?

Well, you’re right — But if something like this happens, you should think about your design. Otherwise, you could do the stuff of super() in your constructor yourself, but that’s bad design, too.

public class GetStuff < public GetStuff(String data) < System.out.println(data); >> public class GetSecondStuff extends GetStuff < private int newData; public GetSecondStuff(String data, int newData) < super(data); this.newData = newData; data = "GetSecondStuff"; System.out.println(data); System.out.println(getAllMyStuffMethod()); >private String getAllMyStuffMethod() < String ret=null; if (this.newData==0) ret="0"; else ret="1"; return "new data : "+ret; >> public class main < public static void main(String[] args) < GetSecondStuff gf2 = new GetSecondStuff("GetStuff",1); >> 

the thing is that line «newData = _newData;» is executed after super(). and the method which I’m trying to override it is executed when calling super(). So using newData there will produce a NullPointerException

Читайте также:  Java update no update table

the class extending the first one may have its own properties, use them.

public class GetSecondStuff extends GetStuff < int _newData public GetSecondStuff(String data, int newData) < super(data); _newData = newData; >private String getAllMyStuffMethod() < if (_newData==0) // do something >> 

the thing is that line _newData = newData; is executed after super(). and the method which I’m trying to override it is executed when calling super().

save the variable newData in an instance-variable. with this u have access to it in the class GetSecondStuff.

public class GetSecondStuff extends GetStuff < private int newData; public GetSecondStuff(String data, int newData) < super(data); this.newData = newData; >private String getAllMyStuffMethod() < if (this.newData==0) // do something >> 

In one of the comments i read that u want to use a subclass-parameter in the super-class. so can u tell me why the new parameter is not in the super-class?

Источник

Extending a class with an extra parameter

Solution 1: I think it would be better (and quite easy) the create more general class that will be able to deal with any number of years you pass to it: If the original class really have to be extended than it can be done like this: I would recommand to change variable names ‘firstYear’ and ‘secondYear’ to something different, like ‘firstPart’, ‘secondPart’ because for extendedPeriod they aren’t years anymore (I left them in my code so it would compile with yours but called the new int ‘thirdPart’). Solution 1: If you want to initialize coordinates by calling new Vector3D(1,2,3): Solution 2: Your parent class (Vector) needs to set the private field.

Extending a class with an extra parameter

I think it would be better (and quite easy) the create more general class that will be able to deal with any number of years you pass to it:

public class Period < int[] years; Period() < >Period(String periode) < String[] periodeSplit = periode.split("-"); years = new int[periodeSplit.length]; for (int i = 0; i < periodeSplit.length; i++) < years[i] = Integer.parseInt(periodeSplit[i]); >> public String toString() < String result = ""; for (int i = 0; i < years.length; i++) < result += "Year " + i + ":" + years[i] + "\n"; >return result; > > 

If the original class really have to be extended than it can be done like this:

class ExtendedPeriod extends Period < int thirdPart; ExtendedPeriod(String periode) < String[] periodeSplit = periode.split("-"); this.firstYear = Integer.parseInt(periodeSplit[0]); this.secondYear = Integer.parseInt(periodeSplit[1]); this.thirdPart = Integer.parseInt(periodeSplit[1]); >public String toString() < return "Day: " + this.firstYear + "\n" + "Month: " + this.secondYear + "\nYear: " + this.thirdPart; >> 

I would recommand to change variable names ‘firstYear’ and ‘secondYear’ to something different, like ‘firstPart’, ‘secondPart’ because for extendedPeriod they aren’t years anymore (I left them in my code so it would compile with yours but called the new int ‘thirdPart’). I don’t feel that this is the best use of inheritance but if that’s what’s needed. I also wanted to reuse toString from Period like this:

but for it to have sense you would have to chagne toString method in Period not to call values ‘years’.

When you extend the class, split it into two variables first, the one that’s different from your current code, and then the one that your current code would handle.

Читайте также:  Javascript get request with headers

Then simply call super(periode)

The child class will have access to the parent variables, since you made them default.

I wouldn’t extend to just add a new year.

Why not make the entire thing generic enough, so that it supports whatever split you need.

public class Period < String [] periodeSplit; Period(String periode) < periodeSplit = periode.split("-"); >public String toString() < //TODO : Iterate and print. >> 

Oop — Java Extending a class and setting values, 6 Answers. Sorted by: 2. You can use private variables instead of protected. This will be more apt. You can use the constructor to set the value of the super class. Edited: public class Animal < private String pig; private String dog; private String cat; public Animal (String pig,String dog,String cat) < this.pig=pig; … Code samplepublic class Animal

Java, extending class with constructor in superclass

abstract class Vector implements sample < private int[] coordinates; public Vector (int[] coordinates)< this.coordinates=coordinates; >> 

If you want to initialize coordinates by calling new Vector3D(1,2,3):

class Vector3D extends Vector < public Vector3D(int n1,int n2,int n3) < super(new int[]); > > 

Your parent class (Vector) needs to set the private field. Currently, the parameter and the instance variable are unrelated.

public abstract class Vector implements Sample < private int[] coordinates; public Vector(int[] coordinates) < this.coordinates = coordinates; >> public class Vector3D < public Vector3D(int[] coordinates) < super(coordinates); >> // usage: new Vector3D(new int[]< 1, 2, 3 >); // Vectors coordinate size: 3. Content: 1, 2, 3 

This would pass the Vector3Ds array to the parent and its size would be the same, as the one provided to the Vector3D class.

Extend Two Classes in Java, It means a class can extend only a single class at a time. Extending more than one class will lead to code execution failure. When a class extends a class, then it is called single inheritance. If a class extends more than one class, it is called multi-inheritance, which is not allowed in Java. Let’s see some examples and …

How to extend class<T extends class&gt

The syntax you’re looking for is

public class MyClass extends Foo  

If you want to extend it with a specific type of T :

public class MyClass extends Foo  

public class Foo < >public class MyClass extends Foo

Java extends example, In this example the variable is protected, meaning it can be read from both the parent and child. The constructor of the classes sets the variable to the desired value. This way you only implement the print function once, and do not need a duplicate overridden method.

How can I extend classes in Factory Method pattern in Java

Well the usage of this pattern wouldn't make much sense, the whole point is that you don't know what implementation of Animal you will get (responsibility separation), so it would be a total anti-pattern to use the knowledge. You can make a new interface Winged or something, and make Flamingo implement it. Then you can always check. remember that bats also fly when thinking of a name 😉

if (animal instanceof Winged)

You can create another interface called WingedAnimal that extends Animal.

public interface WingedAnimal extends Animal < public void fly(); >public class Flamingo implements WingedAnimal < @Override public void breath() <>@Override public void walk() <> @Override public void fly() <> > 

Then write this code while creating Flamingo instance:

WingedAnimal animal = (Flamingo) factory.createAnimal(); 

Your code animal.fly() will work perfectly.

You can use s factory method using generics. A couple of good examples are available

I suggest you read all of them for a good understanding of the problem and possible solution approaches.

Java extends Keyword, The extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: subclass (child) - the class that inherits from another class. superclass (parent) - the class …

Источник

Java Extending a class and setting values

Would this be the correct way to set protected variables? Is using protected variables the correct way to do this? Is there a more professional OO way to do?

@Poindexter using non-final setters in a constructor may have ugly effects if a subclass overrides them. The question should rather be - "why are your setters not final?" 😉

@kostja this is the type of discussion I'm looking for. I need someone to point me the correct approach to this

6 Answers 6

You can use private variables instead of protected. This will be more apt. You can use the constructor to set the value of the super class. Edited:

public class Animal < private String pig; private String dog; private String cat; public Animal(String pig,String dog,String cat)< this.pig=pig; this.dog=dog; this.cat=cat; >> public class AnimalAction extends Animal < public AnimalAction(String pig, String cat, String dog) < super(pig,dog,cat); >> 

You should be able to use this.pig etc, since you inherited the protected members. You could also actually call the public setPig(. ) methods.

It will work, but isn't a good way to do it. There are several more correct ways of doing it in the other answers here.

There is nothing wrong in using protected member variable and then inherit them in subclass .

But If a developer comes along and subclasses your class they may mess it up because they don't understand it fully. With private members, other than the public interface, they can't see the implementation specific details of how things are being done which gives you the flexibility of changing it later. By providing protected member variables you are just coupling tight between you subclass and superclass.

The less your member variables can be seen outside the class, the better. I would make the class variables private and make the getters public (or as required) & the setters protected.

There's no need to use the super prefix, or any other prefix, to access protected variables.

BTW - I disagree with Thomas on one point - do not call the setter methods of the superclass in your constructor. Using non-final setters in a constructor may have ugly effects if a subclass overrides them. Then they could be called on an incompletely constructed object. But you should consider making your setters final if you don't mean them to be overridden.

The principle of "design for inheritance or forbid it" is explained in the Effective Java book by Joshua Bloch.

Источник

Оцените статью