-1

I have a class Den implementing the Serializable interface:

public class Den implements Serializable {

    private double id;
    private String name;

    public Den(double id, String name){
        this.id = id;
        this.name = name;
    }

    public double getId() {
        return id;
    }

    public void setId(double id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

I can send a Den instance in an Intent like this:

Intent intent = new Intent(context, NewActivity.class);
intent.putExtra("OBJECT_KEY", new Den(20.2, "JOHN"));
startActivity(intent);

And receive it in another Activity like this:

Intent intent = getIntent();
Den den = (Den) intent.getSerializableExtra("OBJECT_KEY");

Now my question is: Why do I need to implement the Serializable interface on Den, but not on primitive data types like int, float or String? What is happening internally?

Xaver Kapeller
  • 49,491
  • 11
  • 98
  • 86
dcanh121
  • 4,665
  • 11
  • 37
  • 84
  • Because you can't, which in turn is because they are already defined. All primitives are already serializable, and so is `String`, as you can see from the Javadoc. Your question doesn't make sense. – user207421 Sep 05 '21 at 09:43

3 Answers3

2

Why do I need to implement the Serializable interface on Den, but not on primitive data types like int, float or String?

String is a Serializable and no primitive type.

Primitive types cannot implement interfaces.

The JVM takes care of fields with a primitive type when serializing an object.

wero
  • 32,544
  • 3
  • 59
  • 84
0

Primitive types are already Serializable

In your own types, consider implement the Parcelable interface better than Serializable

There are some plugins for Android Studio that make it very easy to implement and the result is a better performance

Alberto S.
  • 7,409
  • 6
  • 27
  • 46
0

The Intent class already gives you the capability to pass a variety of data types (most of which are primitive) between activities via putExtra(). So you'd only need to implement Serializable on custom objects.

Also like Alberto suggested, it's better practice to implement Parcelable because it's specific to the android platform and likely more optimized. Check this for more info between the two, link

Community
  • 1
  • 1
prettyvoid
  • 3,446
  • 6
  • 36
  • 60