Using superclass to initialise a subclass object java
You may have a method that only takes an instance of SuperClass
. Since SubClass
is a SuperClass
, you can use an instance of SubClass
and treat it as SuperClass
.
The same behavior is used when working with interfaces:
List someList = new ArrayList();
That's the beauty of polymorphism. It allows you to change out the implementation of the class' internals without breaking the rest of your code.
If I use Superclass to initialize a subclass object, why will the object have the attributes of the subclass and but the methods of the superclass?
As Ramkumar says this link might help you
you can not override the structure of a class which is already defined, you can override the behavior. Variables of a class are not polymorphic in nature.
Initialize super class values for an already instantiated subclass object
This can only be done through reflection:
import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) throws IllegalAccessException {
SubClass subClass = new SubClass();
subClass.a = 10;
subClass.b = 10;
SuperClass superClass = new SuperClass();
superClass.c = 30;
for (Field field : SuperClass.class.getDeclaredFields()) {
field.set(subClass, field.get(superClass));
}
System.out.println(subClass.c); // prints out 30
}
}
class SubClass extends SuperClass {
int a;
int b;
}
class SuperClass {
int c;
}
I would however recommend you to not use this approach and just implement a merge(SuperClass superClass)
method in your subclass:
class SubClass extends SuperClass {
int a;
int b;
void merge(SuperClass superClass) {
this.c = superClass.c;
}
}
Superclass Subclass Instantiation
When you create an instance of SubClass
SuperClass superClass = new SubClass();
you can cast superClass
to SubClass
and gain access to the methods of SubClass
. You can't do it when you create an instance of SuperClass
.
In addition, calling methods of SuperClass
on an instance of SubClass
would execute SubClass
methods when SubClass
overrides these methods.
java, initialize SubClass from SuperClass
If you have a List<Base>
, then you cannot convert it to a List<SubClass>
. This is mainly because the list may not contain instances of SubClass
. The best you can do is:
List<SubClass> newList = new List<SubClass>();
for(Base b: list){
if (b instanceof SubClass) {
SubClass sub = (SubClass)b;
. . .
newList.add(sub);
}
}
Generally, however, when you find yourself doing this kind of thing, there's something wrong with your design. You might want to avoid subclassing Base
and using composition instead.
EDIT Based on your comments, it sounds like you want to construct a list of SubClass
instances using a list of Base
instances as a start. One approach is to define a constructor for SubClass
that takes a Base
as an argument.
public class SubClass extends Base{
private boolean selected;
public SubClass() {
// default constructor
}
public SubClass(Base original) {
// copy constructor -- initialize some fields from
// values in original, others with default values
}
...
getter und setter
...
}
Then you can construct your new list with:
List<SubClass> newList = new List<SubClass>();
for(Base b: list){
SubClass sub = new SubClass(b);
. . .
newList.add(sub);
}
Java subclass initialize with arguments of superclass
Update
I resolved the problem thanks to @ScaryWombat user in the comments of question. So the problem was in how i declared 2 things:
The variables, when declared static, were used by all the classes. So, i declared as protected in the class Device and as private in all the other classes.
The method calc_consume_w has the same problem, because i declared as static, so i change it to public.
This two changes resolved the problem, the class App stay the same.
The new code:
class Device
public class Device {
protected float price, basis_price = 100f;
protected byte weight, basis_weight = 1;
protected char consumption_w, basis_consumption_w = 'F';
// ...
public float calc_consume_w() {
HashMap<Character,Float> cost_w = new HashMap<Character,Float>();
cost_w.put('A', 100f); cost_w.put('B', 80f); cost_w.put('C', 60f);
cost_w.put('D', 50f); cost_w.put('E', 30f); cost_w.put('F', 10f);
return cost_w.get(Character.toUpperCase(consumption_w));
}
// ...
}class Tablet:
public class Tablet extends Device {
private float ram, basis_ram = 1;
// ...
}class Laptop:
public class Laptop extends Device {
private float hd, basis_hd = 250;
// ...
}class TotalPrice:
public class TotalPrice {
private float total_devices, total_laptops, total_tablets;
private Device[] devices;
// ...
}
Related Topics
Modifying Existing File Content in Java
Converting to Upper and Lower Case in Java
Find an Array Inside Another Larger Array
Java: How to Do Double-Buffering in Swing
How Does Java Order Items in a Hashmap or a Hashtable
How to Use Urlclassloader to Load a *.Class File
@Preupdate and @Prepersist in Hibernate/JPA (Using Session)
How to Achieve Transfer File Between Client and Server Using Java Socket
Native Query with Named Parameter Fails with "Not All Named Parameters Have Been Set"
How to Attach Multiple Files to an Email Using Javamail
How to Use the Command Update-Alternatives --Config Java
How to Efficiently Remove All Null Elements from a Arraylist or String Array