creating an instance with all the fields of the parent class - java

I have a Pojo named A and another Pojo named B which extends A:
public class A
{
private String name;
//constructor, setter and getter comes here.
}
public class B extends A
{
private long id;
//constructor, setter and getter comes here.
}
i have an instance of class A with a name.
A a = new A();
a.setName("udy");
I would like to get an instance of class B with all the values of a but without knowing what are the fields and values in a
Copy constructor wouldn't do the trick since when adding a field to A, i must update the copy constructor of B
Dozer can do the trick, but i would like to avoid creating a copy.
i did some search but didn't find what i was looking for.
Any suggestion would be really appreciated!

Related

Jackson: should serialization change when class name changes and class inherits from another class?

Suppose I have the following class:
class OrigClass {
private int fieldOne;
private int field Two;
// getters and setters
}
Let's say that I serialize an object of this class, and pass it read it by the class NewClass:
class NewClass extends BaseClass {
private int fieldOne;
// getters and setters
}
class BaseClass {
private int field Two;
// getters and setters
}
As you can see, an object of NewClass has exactly the same properties as the properties of OrigClass. The difference is that class names differ and NewClass inherits fieldOne from BaseClass. In this case, will an error occur in deserialization by NewClass?
If the fields are inherited or not doesn't matter to Jackson, it will check for the setters.
If it can deserialize, it will. You should encounter no issues to serialize OrigClass and deserialize NewClass

Access to ancestors enums

I have a class A which looks like this:
public abstract class A {
protected enum Identifier{
HELLO,WORLD
}
private String identifier;
public void setIdentifier(Identifier identifier){
this.identifier=identifier.toString();
}
public String getIdentifier(){
return identifier;
}
}
Now the class hierarchy is this:
B extends A
C extends A
D extends B
E extends D
or A->B->D->E and A->C
Now if I want to use the setter of Identifier enum of A in E how do I go about it. And also I need to use the getter of the same enum in class C. Do I need to create a separate method in each of the sub classes to access the ancestor?
The approach which I took was:
public abstract class A {
protected enum Identifier{
HELLO,WORLD
}
protected Identifier identifier;
}
In the child class E I am saying identifier = Identifier.HELLO;. I dont know if this is the best approach but even the class C can get the same value of the enum if its part of the same instance. This approach seems to be a bit obfuscate as it is not very clear immediately that where the identifier is inherited from. Any better approach?
Being your code as it is now, you may invoke both the getter and the setter on any sublcass-of-A object, except for one detail: The Identifier enum should be also public, in order to be accessed by any client class.
Public and protected members are automatically inherited by subclasses. Among them, protected members are accessible from subclasses only. And public members are accessible from any client class.

Java Inheritance with already created superclass

Lets say i have a Super class Person and subclass Employee
I would like to create a person class first and then use it as a param to be placed into my employee class's constructor.
E.g. Public Empolyee(Person person....) (This produces a constructor not found error during compile time)
My Case scenario is that i have a Person object that has not been instantiated as an employee yet and later on i would like to use it to instantiate an Employee object and I would like to pass this person's variables over.
So how do i do this? Also please do explain if it should be done this way or not.
You directly get access to all Person class members via Employee class due to the inheritance relationship. You dont need to pass parent object to a child.
Pass all the necessary parameters to Employee and call super() from its constructor.
//Person constructor
Person(param1, param2){
}
class Employee extends Person
//Employee constructor
Employee(param1, param2){
super(param1, param2);
}
// New object
Employee emp = new Employee(param1, param2);
Also constructor dont return anything so remove the void in your question.
Child class automatically gets access of all the public, protected members of the parent and child also has reference to parent class.
why you want to pass parent class reference to Child class. Instead you can call parent class constructor from child class like this:
public Child(){
super()
}
According to the question below, we can do this:
public class Child1 extends Super1 {
private int l;
public Child1(Super1 s){
super(s);
}
public Child1(){
this.l=20;
}
}
public class Super1 {
private int k;
public Super1(){
}
public Super1(Super1 s){
k=s.k;
}
}
i dont see your inheritance logic here correctly.
you have answer already..see below
class person()
class employee extends person(here)
hence you get to access its variables and methods..
just curious why you need to instantiate employee and injecting person class which is already parent to employee.
Your Employee will work as a person.You can call every method or variable (except private variables and methods) of Person by Employee object. But still if you want to pass a Person object to the constructor of Employee class then you can do it as fallows-
public Employee(Person person,.......){
super();//or pass required parameters according to constructor of Person class
//do whatever you want
}
it will work perfectly.
try this:
//if your Person constructor looks like this
public Person(param1, param2){
}
//then your copy constructor would look like this
public Employee(Person p){
super(p.getParam1 p.getParam2);
}

Access Methods of a class from created object of another class

I need little help here. I have three classes Book, Member, Bean.
Book.java
public class Book
{
public Member m=null;
// various getter & setter methods
}
Member.java
public class Member
{
public Book b=null;
// various getter & setter methods
}
In Bean.java I create an object of Book class & through this object we have to access all methods of Book as well as Member class.Now the problem is the object of Member class created in Book is not initialized & we can't use new operator to initialize it & we can't make it static. If we use new operator the result is not come.
This design is not correct.
There is a circular dependency.
Book has a Member and Member has a Book .
You need to double check this design.
Constructor injection would be the easiest way to fix this once you have the dependencies sorted out.
UPDATE : Corrected design which I feel is correct.
//Book
public class Book {
private String bookName;
private String authorName;
//getters and setters
}
//Member will have a book (maybe multiple) associated with them
public class Member {
private Book[] bookArray;
public Member (Book... books) {
this.bookArray = books;
}
}

java, initialize SubClass from SuperClass

public class Base {
//long list of attributes
// no Constructor using fields
// no init methode
// i cannot change this class
}
now i extended the Base Class like:
public class subClass extends Base{
private boolean selected;
...
getter und setter
...
}
i become a list of Base object List<Base>
but i need the same list but as List<SubClass>
is there a way to initialize the Subclass from the Base Class?
example:
for(Base b: list){
SubClass sub = (SubClass)b; // Thats wrong i know
if(...){
sub.setSelected(true);
}
newList.add(sub);
}
i try to avoid the manual init of each Attribute of the Base Class to the SubClass
i update my Question as requested in the Comments:
the Design above is just an example. my QUESTIN EXACTLY IS:
why converting BaseClass into SubClass (sence Subclass extends BaseClass) is not Possible? why Java dosn't allow me to do the following:
example:
Class Base{
private String name;
.....
}
Class SubClass extends Base{
private String title;
}
then
Base b = DBController.getById(...);
SubClass sub = (SubClass)b;
after that the Object sub should have the Attribute Name from the Object b
and the title Attribute is null
why is this not the case in java?
sorry for my bad english,
thanks
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);
}
There is a way: Various Java Beans spec based manipulation.
For example:
Commons BeanUtils
for( Base base: list ){
SubClass sub = new SubClass();
PropertyUtilsBean.copyProperties( sub, base );
if(...){
sub.setSelected(true);
}
newList.add(sub);
}
This works based on get/setters of the same name. Doesn't copy internal fields.
If you needed to copy internal fields, it's actually not that hard to implement using javax.lang.reflect.
You appear to have a class with a lot of attributes and no easy way of setting them all. You have now run in to a problem where you need a class with an additional attribute but you have to deal with that mess of a base class.
I suggest that, instead of creating a subclass and casting, you create a wrapper class around the ugly one:
public class BigDumbClass {
// A lot of attributes
// No Constructor
// No init method
}
public class Wrapper {
private BigDumbClass base;
private boolean selected;
public Wrapper(BigDumbClass base) {
this.base = base;
this.selected = false;
}
//getters and setters
}
Now when you have to create that new list you can wrap everything in the old list
List<BigDumbClass> oldList = someData();
List<Wrapper> wraps = aNewList();
for (BigDumbClass bigDumb : oldList) {
Wrapper wrap = new Wrapper(bigDumb);
if (someCondition()) {
wrap.setSelected(true);
}
wraps.add(wrap);
}
Ideally, BigDumbClass would implement an interface that Wrapper could also implement, allowing the wrapper to defer all of the calls to the instance it has wrapped.
public class BigDumbClass implements SharedInterface {
// All the stuff outlined above
}
public class Wrapper implements SharedInterface {
// All the stuff outlined above
// Methods defined in SharedInterface
public void doSomething() {
base.doSomething();
}
}
Otherwise, you can provide a getter to the instance and access it directly.
BigDumbClass base = wrapper.getBase();
base.doSomething();

Categories

Resources