Data data = new Data("path"); //I read data from excel and save. This code is in Main.
public abstract class Generator{
public abstract double[][] generate();
//here I need reference - data
}
public class GeneratorA extends Generator{
public double[][] generate(){
//first implementation - I want to work with data
}
}
public class GeneratorB extends Generator{
public double[][] generate(){
//second implementation - I want to work with data
}
}
What I need is passing reference (data) to abstract class Generator. I can pass reference in constructors of GeneratorA/GeneratorB but I have more child classes and it is inefficient. Is any way how to pass reference data to abstr. class Generator? I just want to inherit reference from class Generator...
Thanks!
You must add a constructor to your abstract class. Then you just have to call super(data) in subclasses constructor.
See the code bellow:
public abstract class Generator{
Data data;
public Generator(Data data) {
this.data = data;
}
public abstract double[][] generate();
//here I need reference - data
}
}
public class GeneratorA extends Generator{
public GeneratorA(Data data) {
super(data);
}
public double[][] generate(){
//first implementation - I want to work with data
}
}
public class GeneratorB extends Generator{
public GeneratorB(Data data) {
super(data);
}
public double[][] generate(){
//second implementation - I want to work with data
}
}
An abstract class can have non-abstract methods and constructors.
public abstract class Generator{
Generator(....)
{
//set here
}
public abstract double[][] generate();
//here I need reference - data
}
You could use the constructor to set the values in the subclass.
OR
If for some reason you don't want to add a constructor/non-abstract method to the abstract class Generator ,you could add one more class which extends Generator and the other subclasses could extend this new class.
You could write a method in the new class for setting values and use it.
It seems from your description you need the same data reference in all Generator objects in this case you can store data as a static field in the abstract class and access in objects of sub classes like:
public abstract class Generator{
static Data data;
public static void setData(Data data){
Generator.data=data;
}
public abstract double[][] generate();
}
Data data = new Data("path");
Generator.setData(data);
public class GeneratorA extends Generator{
public double[][] generate(){
//here you can work with data..
}
}
Related
i am wondering what happens with object variables in abstract classes in Java. For example if have this abstract class:
public abstract class BaseClass{
private int[] myNumbers;
public Baseclass(int length){
myNumbers = new int[length];
}
public boolean isOne(int index){
return myNumbers[index] == 1;
}
}
and i have this real class which extends the BaseClass:
public class ArrayClass extends BaseClass{
private int[] myNumbers; //i have to define it again?
public ArrayClass(int length){
super(length); //does this affect my array? I don't think so
}
public void setValue(int index, int value){
if(!isOne(index))
myNumbers[index] = value;
}
}
I want to define basic operations in my BaseClass and do some other stuff in my normal ArrayClass. Because i need an array in my BaseClass i have to define one to work with it in the different methods (obviously).
But in my ArrayClass which extends BaseClass i have to define another array. I am not sure why this is and if it needs to be this way? I hope you understand what i mean. For example i could utilize the BaseClass a second time for this normal class:
public class ArrayClass2 extends BaseClass{
private int[] myNumbers;
public ArrayClass2(int length){
super(length);
}
public int getValue(int index){
if(!isOne(index))
return myNumbers[index];
else
return 1;
}
}
The myNumbers array needs to be protected, not private in order to be accessible from within a sub class.
Read more: https://www.tutorialspoint.com/java/java_access_modifiers.htm
Java has four access types. You can read about them here.
If you want to expose the field in your base class to its children, you can use protected modifier.
I have some strange question.
I have an interface in java:
public interface Inventory{
public void add(// take an object of a class);
public int delete(// take an object of a class);
public int edit(// take an object of a class);
}
then i wrote a class that implements the interface.
public class Supply implements Inventory{
public void add( // object of some class) {}
public int edit( // object of some class) {}
public int delete( // object of some class) {}
}
then i wrote another class that implements the interface but with different object name in parentheses.
public class support implements Inventory{
public void add(// object of different class) {}
public int edit(// object of different class) {}
public int delete(// object of different class) {}
}
my question is: what is the parameter that must be written in interface methods in order to make the other classes take any object name that would like to implement in its own way.
That is what generics are for. You can have an interface Inventory<T> with a method void add(T t). Then you can have a class that implements Inventory<Product> with a method add(Product p) but you could also have a class that implements Inventory<Supplier> with a method void add(Supplier s).
I have an abstract class that should implement a public field, this field is an interface or another abstract classe.
something like this:
public abstract class GenericContainer {
public GenericChild child;
}
public abstract class GenericChild {
public int prop1=1;
}
public abstract class SpecialChild extends GenericChild {
public int prop1=2;
}
Now i have another specialized class Container:
public abstract class SpecialContainer extends GenericContainer {
public SpecialChild child=new SpecialChild(); //PAY ATTENTION HERE!
}
Java allow me to compile this, and i IMAGINE that the field child in SpecialContainer is automatically overloading the field child of the GenericContainer...
The questions are:
Am i right on this? The automatic 'overloading' of child will happen?
And, more important question, if i have another class like this:
public class ExternalClass {
public GenericContainer container=new SpecialContainer();
public int test() {
return container.child.prop1
}
}
test() will return 1 or 2? i mean the GenericContainer container field what prop1 will call, the generic or the special?
And what if the special prop1 was declared as String (yes java allow me to compile also in this case)?
Thanks!
In Java, data members/attributes are not polymorphic. Overloading means that a field will have a different value depending from which class it's accessed. The field in the subclass will hide the field in the super-class, but both exists. The fields are invoked based on reference types, while methods are used of actual object. You can try it yourself.
It's called, variable hiding/shadowing, for more details look on here
It isn't overriding anything, you're just hiding the original field at the current class scope. If you use a variable with the subtype you will still be able to access the original property. Example:
abstract class GenericContainer {
public GenericChild child;
}
abstract class GenericChild {
public int prop1=1 ;
}
class SpecialChild extends GenericChild {
public int prop1=2;
}
class SpecialContainer extends GenericContainer {
public SpecialChild child;
}
public class Main {
public static void main( String ... args ) {
GenericContainer container = new SpecialContainer();
container.child = new SpecialChild();
System.out.println( container.child.prop1 );
SpecialChild child = (SpecialChild) container.child;
System.out.println( child.prop1 );
}
}
This prints 1 and then 2.
From SpecialChild you would also be able to go up one level using super:
class SpecialChild extends GenericChild {
public int prop1=2;
public int getOriginalProp1() {
return super.prop1;
}
}
Regarding
....and i IMAGINE that the field "child" in SpecialContainer is automatically overloading the field 'child' of the GenericContainer...
No. Fields don't get overridden, only methods do.
This is one reason why use of (overridable) getter and setter methods are preferred to direct access to fields. Your fields should almost all be private.
As for your design, there's no need for your SpecialContainer class to have a SpecialChild field, but instead the SpecialChild object should be placed in the GenericChild field.
Why nobody is observing that program will throw NullPointerException.
subclass's field with same name will hide super class's field. There is no overriding with field. Overriding is only possible with methods.
Original Code by Author:
public abstract class GenericContainer {
public GenericChild child;
}
public abstract class GenericChild {
public int prop1=1;
}
public abstract class SpecialChild extend GenericChild {
public int prop1=2;
}
public abstract class SpecialContainer extends GenericContainer {
public SpecialChild child=new SpecialChild(); //PAY ATTENTION HERE!
}
public class ExternalClass {
public GenericContainer container=new SpecialContainer();
public int test() {
return container.child.prop1
}
}
Java allow me to compile this, and i IMAGINE that the field "child" in
SpecialContainer is automatically overloading the field 'child' of the
GenericContainer...
Firstly, Inheritence doesn't apply to variables. Fields(Insatnce variables) are not overridden in your sub-class.they are only visible in your subclass if they are marked with either public, protected or default.
To answer your question it maintains both instances. And depending on how you refer to the container (either through the abstract or the impl) determines which variable you are referring to.
public class Test {
public abstract class Container{
public Generic gen = new Generic();
}
public class ContainerImpl extends Container{
public GenericImpl gen = new GenericImpl();
}
public class Generic{
public int prop = 0;
}
public class GenericImpl extends Generic{
public int prop = 1;
}
public Test(){
Container c = new ContainerImpl();
System.out.println(c.gen.prop); // Outputs "0"
System.out.println(((ContainerImpl)c).gen.prop); // Output "1"
}
public static void main(String[] args) {
new Test();
}
}
The bigger question at hand is, why would you design something like this? I'm assuming you are asking from a theoretical perspective.
My 2 cents, this isn't great OO design. You would be better off making the public variables private and assigning their values through a constructor or property setter. As-is, it will lead to unexpected results in your code.
I have tree classes.
class MyObject{
public void DoSomething()
{
here I need to call method add from class base.
}
}
class base
{
protected final void add(){}
}
class extended extends base {
private MyObject pObject = new MyObject();
...
{
pObject.DoSomething();
}
}
I could have created class for each variation that extends class extended, but the type what I need to use becomes available only after class extended is already initiated.
How do I call base.add() from MyObject inner method?
You can do it in a couple of ways:
Have a reference of your extended class in MyObject class. When you instantiate MyObject variable in extended class, pass it the reference of extended.
Something like this:
class MyObject{
private base baseObj;
public MyObject(base baseObj){
this.baseObj = baseObj;
}
public void DoSomething()
{
//here I need to call method add from class base.
//use baseObj to call the methods
}
}
class base
{
protected final void add(){}
}
class extended extends base {
private MyObject pObject;
...
public extended(){
pObject = new MyObject(this);
}
{
pObject.DoSomething();
}
}
Declare the methods in base class static. This way you can call the methods without requiring an instance of the base class.
Something like this:
class MyObject{
public void DoSomething()
{
//here I need to call method add from class base.
//call like this
base.add();
}
}
class base
{
protected static final void add(){}
}
class extended extends base {
private MyObject pObject;
...
public extended(){
pObject = new MyObject(this);
}
{
pObject.DoSomething();
}
}
One more thing: This is off-topic, but you might want to read about Java Naming Conventions. Having class names start with lowercase is something that you wouldn't find in the naming conventions.
dummy code like this:
class MyObject{
public void DoSomething(Base base)
{
base.add();
}
}
class extended extends base {
private MyObject pObject = new MyObject();
...
{
pObject.DoSomething(this);
}
}
So I've come across a bit of a snag in some code that I'm working with. Essentially I have the following three tidbits of code:
Abstract class:
public abstract class TestParent {
int size;
public TestParent(int i){
size = i;
}
}
Child Class:
public class TestChild extends TestParent{
public void mult(){
System.out.println(this.size * 5);
}
}
Implementation:
public class TestTest {
public static void main(String args[]) {
TestChild Test = new TestChild(2);
Test.mult();
}
}
Consider the following case of abstract class and extends implementation.
https://stackoverflow.com/a/260755/1071979
abstract class Product {
int multiplyBy;
public Product( int multiplyBy ) {
this.multiplyBy = multiplyBy;
}
public int mutiply(int val) {
return muliplyBy * val;
}
}
class TimesTwo extends Product {
public TimesTwo() {
super(2);
}
}
class TimesWhat extends Product {
public TimesWhat(int what) {
super(what);
}
}
The superclass Product is abstract and has a constructor. The concrete class TimesTwo has a default constructor that just hardcodes the value 2. The concrete class TimesWhat has a constructor that allows the caller to specify the value.
NOTE: As there is no default (or no-arg) constructor in the parent abstract class the constructor used in subclasses must be specified.
Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class.
public class TestChild extends TestParent{
public TestChild(int i){
super(i); // Call to the parent's constructor.
}
public void mult(){
System.out.println(super.size * 5);
}
}
Use super to call parent (TestParent.TestParent(int)) constructor:
public class TestChild extends TestParent{
public TestChild(int i) {
super(i);
}
//...
}
or if you want to use some constant:
public TestChild() {
super(42);
}
Note that there is no such thing as abstract constructor in Java. Essentially there is only one constructor in TestParent which must be called before calling TestChild constructor.
Also note that super() must always be the first statement.
When you have explicit constructor defined in super class and no constructor without arguments defined, your child class should explicitly call the super class constructor.
public class TestChild extends TestParent{
TestChild ()
{
super(5);
}
}
or, if you don't want call super class constructor with parameters, you need to add constructor with no arguments in super class.
public abstract class TestParent {
int size;
public TestParent(){
}
public TestParent(int i){
size = i;
}
}
You code wont compile because your base class does not have a default constructor. Either you need to provide it in base class or you need to provide parameterized constructor in derived class and invoke super.
public class TestChild extends TestParent{
public TestChild (int i)
{
super(i * 2);
}
}
This code would use the double of i. This is an overriding, though i'm not sure what you want to ask.
Other solution:
public class TestChild extends TestParent{
public TestChild (int i)
{
super(i);
this.size = 105;
}
}
For this solution, size must be protected or public.