Pacha
Pacha

Reputation: 1526

Java transform child class to parent one

Consider this code:

public class PublicInformation
{
    public String username;
    public String status;
}

public class PrivateInformation extends PublicInformation
{
    public String somePrivateInformation;
}

I have a PrivateInformation object, and I want to send it to store it on a stream, without the values of PrivateInformation. So I want to convert it to a PublicInformation object.

How should I do this? Is casting it to a PublicInformation object and send it through a stream enough?

Upvotes: 0

Views: 326

Answers (3)

Kabulan0lak
Kabulan0lak

Reputation: 2136

Create a function that transforms you PrivateInformation into a PublicInformation, then send it :

public class PublicInformation
{
    public String username;
    public String status;
}

public class PrivateInformation extends PublicInformation
{
    public String somePrivateInformation;

    public PublicInformation prepareToSend(){
        return new PublicInformation(){username = this.username, status = this.status};
    }
}

Then you can call PrivateInformation.prepareToSend() to store it

Upvotes: 1

user1907906
user1907906

Reputation:

Implement a cunstructor for PublicInformation that takes an instance of PublicInformation as a parameter.

public PublicInformation(PublicInformation other) {
  this.username = other.getUsername();
  this.status = other.getStatus();
}

Then call this constructor with an instance of PrivateInformation:

PrivateInformation privateInformation = new PrivateInformation();
// set username, status, and somePrivateInformation

PublicInformation publicInformation = new PublicInformation(privateInformation);

The resulting publicInfromation will be what you want.

Upvotes: 0

Markus
Markus

Reputation: 773

Depending where your stream is. If it is a stream controlled by you, simply pass on the object. If it is a stream out of your control you must remove all the unnecessary data.

I see two solutions:

PrivateInformation privateInfo = new PrivateInformation();
...
privateInfo.setSomePrivateInformation(null);
...

or you write your own converter

public interface Converter<T, S>{
    public <S> convert(T src, S target)
}


public MyConverter implements Converter<PrivateInfo, PublicInfo> {
    public <S> convert(T src, S target) {
        PublicInfo tmp = new PublicInfo();
        tmp.setA(target.getA());
        tmp.setB(target.getB());

        return tmp;
    }
}

Upvotes: 0

Related Questions