Interfaces Java Interface Notes

Total Page:16

File Type:pdf, Size:1020Kb

Interfaces Java Interface Notes Interfaces Interfaces & • What is an interface? Informally, it is a specification subtyping of how an agent interacts with the outside world • Java has a construct called interface which is Lecture 4 used formally for this purpose – an interface describes how a class interacts with its clients CS 2112 – Spring 2014 – method names, argument/return types, fields 2 Java interface Notes interface IPuzzle { • name of interface: void scramble(); IPuzzle int tile(int r, int c); • An interface is not a class! boolean move(char d); • a class implements – cannot be instantiated } this interface by – incomplete specification implementing class IntPuzzle implements IPuzzle { public instance public void scramble() {...} methods as • class header must assert implements I for Java to public int tile(int r, int c) {...} specified in the recognize that the class implements interface I public boolean move(char d) {...} } interface • the class may • A class may implement several interfaces: implement other class X implements IPuzzle, IPod {...} methods 3 4 Why an interface construct? Why an interface construct? • good software engineering • Lots of examples in Java – specify and enforce boundaries between different parts of a team project Map<String, Command> h • can use interface as a type = new HashMap<String, Command>(); – allows more generic code List<Object> t = new ArrayList<Object>(); – reduces code duplication Set<Integer> s = new HashSet<Integer>(); 5 6 Example of code duplication class Client{ IntPuzzle p1 = new IntPuzzle(); ArrayPuzzle p2 = new ArrayPuzzle(); • Suppose we have two implementations of puzzles: ...display(p1)...display(p2)... – class IntPuzzle uses an int to hold state public static void display(IntPuzzle p){ – class ArrayPuzzle uses an array to hold state for (int r = 0; r < 3; r++) for (int c = 0; c < 3; c++) Code duplicated System.out.println(p.tile(r,c)); because • Say the client wants to use both implementations } IntPuzzle – perhaps for benchmarking both implementations to pick the and best one public static void display(ArrayPuzzle p){ ArrayPuzzle – client code has a display method to print out puzzles for (int r = 0; r < 3; r++) are different for (int c = 0; c < 3; c++) System.out.println(p.tile(r,c)); • What would the method look like? } display } 7 8 One Solution ― Abstract Classes abstract class Puzzle { Observation abstract int tile(int r, int c); ... } • Two display methods are needed because class IntPuzzle extends Puzzle { IntPuzzle and ArrayPuzzle are different types, Puzzle public int tile(int r, int c) {...} code ... and parameter p must be one or the other } class ArrayPuzzle extends Puzzle { public int tile(int r, int c) {...} • but the code inside the two methods is identical! ... } – code relies only on the assumption that the object p has an instance method tile(int,int) public static void display(Puzzle p){ • Is there a way to avoid this code duplication? Client for (int r = 0; r < 3; r++) code for (int c = 0; c < 3; c++) System.out.println(p.tile(r,c)); }} 9 10 Another Solution ― Interfaces IPuzzle interface IPuzzle { int tile(int r, int c); ... } IntPuzzle ArrayPuzzle class IntPuzzle implements IPuzzle { Puzzle public int tile(int r, int c) {...} code ... } • interface names can be used in type declarations class ArrayPuzzle implements IPuzzle { – IPuzzle p1, p2; public int tile(int r, int c) {...} ... } • a class that implements the interface is a subtype of the interface type public static void display(IPuzzle p){ – IntPuzzle and ArrayPuzzle are subtypes of IPuzzle Client for (int r = 0; r < 3; r++) – IPuzzle is a supertype of IntPuzzle and ArrayPuzzle code for (int c = 0; c < 3; c++) System.out.println(p.tile(r,c)); }} 11 12 Extending a Class vs Interfaces IPuzzle IPod IRon Implementing an Interface • A class can Classes AClass BClass – implement many interfaces, but – extend only one class • Unlike classes, types do not form a tree! • To share code between two classes – a class may implement several interfaces – put shared code in a common superclass – an interface may be implemented by several classes – interfaces cannot contain code 13 14 Static vs Dynamic Types Example int i = 3, j = 4; • Every variable (more generally, every expression that denotes some kind of data) has a static* or compile- Integer x = new Integer(i+3*j-1); time type System.out.println(x.toString()); – derived from declarations – you can see it – known at compile time, without running the program • static type of the variables i,j and the expression i – does not change +3*j-1 is int • static type of the variable x and the expression • Every object has a dynamic or runtime type new Integer(i+3*j-1) is Integer – obtained when the object is created using new • static type of the expression x.toString() is – not known at compile time – you can’t see it String (because toString() is declared in the class Integer to have return type String) * Warning! No relation to Java keyword static • dynamic type of the object created by the execution of is 15 new Integer(i+3*j-1) Integer 16 Reference vs Primitive Types Why Both int and Integer? x: • Reference types • Some data structures work only with reference types – classes, interfaces, arrays ( ) (Integer) Hashtable, Vector, Stack, ... – E.g.: Integer int value: 13 String toString() ... • Primitive types are more efficient for (int i = 0; i < n; i++) {...} • Primitive types – int, long, short, byte, boolean, char, float, double x: 13 17 18 Upcasting Upcasting and Downcasting • Example of upcasting: • Applies to reference types only • Used to assign the value of an expression of one Object x = new Integer(13); (static) type to a variable of another (static) type – static type of expression on rhs is Integer – upcasting: subtype → supertype – static type of variable x on lhs is Object – downcasting: supertype → subtype – Integer is a subtype of Object, so this is an upcast • A crucial invariant: • static type of expression on rhs must be a subtype of If during execution, an expression E is ever evaluated static type of variable on lhs – compiler checks this and its value is an object O, then the dynamic type of O is a subtype of the static type of E. • upcasting is always type correct – preserves the invariant automatically 19 20 Downcasting Is the Runtime Check Necessary? • Example of downcasting: Yes, because dynamic type of object may not be known at compile time Integer x = (Integer)y; – static type of y is Object (say) void bar() { – static type of x is Integer foo(new Integer(13)); } – static type of expression (Integer)y is Integer String(“x”) – Integer is a subtype of Object, so this is a downcast void foo(Object y) { • In any downcast, dynamic type of object must be a int z = ((Integer)y).intValue(); ... subtype of static type of cast expression } • runtime check, ClassCastException if failure • needed to maintain invariant (and only time it is needed) 21 22 Upcasting with Interfaces Why Upcasting? • Java allows up-casting: IPuzzle p1 = new ArrayPuzzle(); • Subtyping and upcasting can be used to avoid code IPuzzle p2 = new IntPuzzle(); duplication • Puzzle example: you and client agree on interface • Static types of right-hand side expressions are IPuzzle ArrayPuzzle and IntPuzzle, resp. interface IPuzzle { void scramble(); • Static type of left-hand side variables is IPuzzle int tile(int r, int c); boolean move(char d); • Rhs static types are subtypes of lhs static type, so } this is ok 23 24 Solution Method Dispatch interface IPuzzle { int tile(int r, int c); public static void display(IPuzzle p) { ... for (int row = 0; row < 3; row++) } for (int col = 0; col < 3; col++) class IntPuzzle implements IPuzzle { System.out.println(p.tile(row,col)); Puzzle public int tile(int r, int c) {...} } code ... } class ArrayPuzzle implements IPuzzle { public int tile(int r, int c) {...} • Which tile method is invoked? ... } – depends on dynamic type of object p (IntPuzzle or ArrayPuzzle) public static void display(IPuzzle p){ – we don't know what it is, but whatever it is, we Client for (int r = 0; r < 3; r++) know it has a tile method (since any class that code for (int c = 0; c < 3; c++) System.out.println(p.tile(r,c)); implements IPuzzle must have a tile method) }} 25 26 Method Dispatch Note on Casting public static void display(IPuzzle p) { for (int row = 0; row < 3; row++) for (int col = 0; col < 3; col++) • Up- and downcasting merely allow the System.out.println(p.tile(row,col)); } object to be viewed at compile time as a different static type • Compile-time check: does the static type of p • Important: when you do a cast, either up (namely IPuzzle) have a tile method with or down, nothing changes the right type signature? If not error → – not the dynamic type of the object • Runtime: go to object that is the value of , p – not the static type of the expression find its dynamic type, look up its tile method • The compile-time check guarantees that an appropriate tile method exists 27 28 Another Use of Upcasting Java instanceof Heterogeneous Data Structures • Example: if (p instanceof IntPuzzle) {...} • Example: IPuzzle[] pzls = new IPuzzle[9]; • true if dynamic type of p is a subtype of pzls[0] = new IntPuzzle(); IntPuzzle pzls[1] = new ArrayPuzzle(); • expression pzls[i] is of type IPuzzle • usually used to check if a downcast will succeed • objects created on right hand sides are of subtypes of IPuzzle 29 30 Example Avoid Useless Downcasting • suppose twist is a method implemented void moveAll(IPuzzle[] pzls) { only in IntPuzzle for (int i = 0; i < pzls.length; i++) { if (pzls[i] instanceof IntPuzzle) void twist(IPuzzle[] pzls) { bad ((IntPuzzle)pzls[i]).move("N"); else ((ArrayPuzzle)pzls[i]).move("N"); for (int i = 0; i < pzls.length; i++) { }} if (pzls[i] instanceof IntPuzzle) { IntPuzzle p = (IntPuzzle)pzls[i]; p.twist(); } void moveAll(IPuzzle[] pzls) { } for (int i = 0; i < pzls.length; i++) } good pzls[i].move("N"); } 31 32 Coercions Subinterfaces • Sometimes Java will let you use a type as if it were another type but does an • Suppose you want to extend the interface to implicit coercion/conversion to the target include more methods type.
Recommended publications
  • Interface Types for Haskell
    Interface Types for Haskell Peter Thiemann and Stefan Wehr Institut f¨urInformatik, Universit¨atFreiburg, Germany {thiemann,wehr}@informatik.uni-freiburg.de Abstract. Interface types are a useful concept in object-oriented pro- gramming languages like Java or C#. A clean programming style advo- cates relying on interfaces without revealing their implementation. Haskell’s type classes provide a closely related facility for stating an in- terface separately from its implementation. However, there are situations in which no simple mechanism exists to hide the identity of the imple- mentation type of a type class. This work provides such a mechanism through the integration of lightweight interface types into Haskell. The extension is non-intrusive as no additional syntax is needed and no existing programs are affected. The implementation extends the treat- ment of higher-rank polymorphism in production Haskell compilers. 1 Introduction Interfaces in object-oriented programming languages and type classes in Haskell are closely related: both define the types of certain operations without revealing their implementations. In Java, the name of an interface also acts as an interface type, whereas the name of a type class can only be used to constrain types. Interface types are a proven tool for ensuring data abstraction and information hiding. In many cases, Haskell type classes can serve the same purpose, but there are situations for which the solutions available in Haskell have severe drawbacks. Interface types provide a simple and elegant solution in these situations. A modest extension to Haskell provides the simplicity and elegance of interface types: simply allow programmers to use the name of a type class as a first- class type.
    [Show full text]
  • Chapter 8. Deploying an Osgi Service
    Chapter 8. Deploying an OSGi Service The OSGi core framework defines the OSGi Service Layer, which provides a simple mechanism for bundles to interact by registering Java objects as services in the OSGi service registry. One of the strengths of the OSGi service model is that any Java object can be offered as a service: there are no particular constraints, inheritance rules, or annotations that must be applied to the service class. This chapter describes how to deploy an OSGi service using the OSGi blueprint container. The Blueprint Container ........................................................................................................... 92 Blueprint Configuration ................................................................................................... 93 Defining a Service Bean .................................................................................................. 95 Exporting a Service ........................................................................................................ 98 Importing a Service ...................................................................................................... 104 Publishing an OSGi Service .................................................................................................... 113 Accessing an OSGi Service ..................................................................................................... 118 FUSE ESB Deploying into the OSGi Container Version 4.2 91 Chapter 8. Deploying an OSGi Service The Blueprint Container Blueprint Configuration
    [Show full text]
  • Mixin-Based Programming in C++1
    Mixin-Based Programming in C++1 Yannis Smaragdakis Don Batory College of Computing Department of Computer Sciences Georgia Institute of Technology The University of Texas at Austin Atlanta, GA 30332 Austin, Texas 78712 [email protected] [email protected] Abstract. Combinations of C++ features, like inheritance, templates, and class nesting, allow for the expression of powerful component patterns. In particular, research has demonstrated that, using C++ mixin classes, one can express lay- ered component-based designs concisely with efficient implementations. In this paper, we discuss pragmatic issues related to component-based programming using C++ mixins. We explain surprising interactions of C++ features and poli- cies that sometimes complicate mixin implementations, while other times enable additional functionality without extra effort. 1 Introduction Large software artifacts are arguably among the most complex products of human intellect. The complexity of software has led to implementation methodologies that divide a problem into manageable parts and compose the parts to form the final prod- uct. Several research efforts have argued that C++ templates (a powerful parameteriza- tion mechanism) can be used to perform this division elegantly. In particular, the work of VanHilst and Notkin [29][30][31] showed how one can implement collaboration-based (or role-based) designs using a certain templatized class pattern, known as a mixin class (or just mixin). Compared to other techniques (e.g., a straightforward use of application frameworks [17]) the VanHilst and Notkin method yields less redundancy and reusable components that reflect the structure of the design. At the same time, unnecessary dynamic binding can be eliminated, result- ing into more efficient implementations.
    [Show full text]
  • Interface Evolution Via Virtual Extension Methods Brian Goetz Fourth Draft, June 2011
    Interface evolution via virtual extension methods Brian Goetz Fourth draft, June 2011 1. Problem statement Once published, it is impossible to add methods to an interface without breaking existing implementations. (Specifically, adding a method to an interface is not a source- compatible change.) The longer the time since a library has been published, the more likely it is that this restriction will cause grief for its maintainers. The addition of closures to the Java language in JDK 7 place additional stress on the aging Collection interfaces; one of the most significant benefits of closures is that it enables the development of more powerful libraries. It would be disappointing to add a language feature that enables better libraries while at the same time not extending the core libraries to take advantage of that feature1. V1 of the Lambda Strawman proposed C#-style static extension methods as a means of creating the illusion of adding methods to existing classes and interfaces, but they have significant limitations – for example, they cannot be overridden by classes that implement the interface being extended, so implementations are stuck with the “one size fits all” implementation provided as an extension2, and they are not reflectively discoverable. 2. Virtual extension methods3 In this document, we outline a mechanism for adding new methods to existing interfaces, which we call virtual extension methods. Existing interfaces can be augmented without compromising backward compatibility4 by adding extension methods to the interface, whose declaration would contain instructions for finding the default implementation in the event that implementers do not provide a method body.
    [Show full text]
  • Dynamic Interfaces
    Dynamic Interfaces Vasco T. Vasconcelos Simon J. Gay Antonio´ Ravara Departamento de Informatica´ Department of Computing Science SQIG at Instituto de Telecomunicac¸oes˜ Faculdade de Cienciasˆ da University of Glasgow, UK Department of Mathematics, IST, Universidade de Lisboa, Portugal [email protected] Technical University of Lisbon, Portugal [email protected] [email protected] Nils Gesbert Alexandre Z. Caldeira Department of Computing Science Departamento de Informatica´ University of Glasgow, UK Faculdade de Cienciasˆ da [email protected] Universidade de Lisboa, Portugal [email protected] Abstract 1. Introduction We define a small class-based object-oriented language in which Standard class-based object-oriented languages present the pro- the availability of methods depends on an object’s abstract state: grammer with the following view: an object is declared to belong to objects’ interfaces are dynamic. Each class has a session type which a certain type, and the type defines various methods; it is therefore provides a global specification of the availability of methods in possible at any time to call any of the methods described in the type. each state. A key feature is that the abstract state of an object However, there are often semantic reasons why it is not appropriate may depend on the result of a method whose return type is an to call a particular method when the object is in a particular inter- enumeration. Static typing guarantees that methods are only called nal state. For example: with a stack, one should not attempt to pop when they are available.
    [Show full text]
  • Create Mixins with Interfaces and Extension Methods by Bill Wagner
    Create Mixins with Interfaces and Extension Methods by Bill Wagner Mixins are small utility classes that define some useful functionality that will usually become part of something larger. For example, a class that implements a serial number to uniquely identify an object, or a timestamp that reports when an object was created. In C++, these mixin classes would be created using regular class definitions, and larger classes that wanted to use the mixin behavior would simply inherit from the mixin, in addition to any base classes it needed. Because the .NET Framework does not support multiple inheritance, we’ve typically used interface to define mixins. That works, but it’s not as powerful. One of the limitations of using interfaces to define mixin behavior is that every class that implements an interface must reimplement every method defined in that interface. That leads many developers to creating minimal interface definitions. (IEqualityComparer<T> has one method, IComparable<T> has only method). In those instances, the interface’s full functionality is completely defined in those small methods. But, what about cases where your interface can, or should, contain many more methods in order to support the developers that want to use the interface? That’s a perfect use case for extension methods. By creating extension methods using the interface, you can inject many more methods into the public definition of the interface, without forcing every developer to re-create those methods whenever he or she implements that interface. I’ve created a simple example based on strings that represent file paths. I often write classes that contain files or directories, usually for offline caches, or similar needs.
    [Show full text]
  • Variable-Arity Generic Interfaces
    Variable-Arity Generic Interfaces T. Stephen Strickland, Richard Cobbe, and Matthias Felleisen College of Computer and Information Science Northeastern University Boston, MA 02115 [email protected] Abstract. Many programming languages provide variable-arity func- tions. Such functions consume a fixed number of required arguments plus an unspecified number of \rest arguments." The C++ standardiza- tion committee has recently lifted this flexibility from terms to types with the adoption of a proposal for variable-arity templates. In this paper we propose an extension of Java with variable-arity interfaces. We present some programming examples that can benefit from variable-arity generic interfaces in Java; a type-safe model of such a language; and a reduction to the core language. 1 Introduction In April of 2007 the C++ standardization committee adopted Gregor and J¨arvi's proposal [1] for variable-length type arguments in class templates, which pre- sented the idea and its implementation but did not include a formal model or soundness proof. As a result, the relevant constructs will appear in the upcom- ing C++09 draft. Demand for this feature is not limited to C++, however. David Hall submitted a request for variable-arity type parameters for classes to Sun in 2005 [2]. For an illustration of the idea, consider the remarks on first-class functions in Scala [3] from the language's homepage. There it says that \every function is a value. Scala provides a lightweight syntax for defining anonymous functions, it supports higher-order functions, it allows functions to be nested, and supports currying." To achieve this integration of objects and closures, Scala's standard library pre-defines ten interfaces (traits) for function types, which we show here in Java-like syntax: interface Function0<Result> { Result apply(); } interface Function1<Arg1,Result> { Result apply(Arg1 a1); } interface Function2<Arg1,Arg2,Result> { Result apply(Arg1 a1, Arg2 a2); } ..
    [Show full text]
  • Using the Bridge Design Pattern for Osgi Service Update
    Using the Bridge Design Pattern for OSGi Service Update Hans Werner Pohl Jens Gerlach {hans,jens}@first.fraunhofer.de Fraunhofer Institute for Computer Architecture and Software Technology (FIRST) Berlin Germany Abstract In the OSGi framework, components cooperate by sharing service objects. The suggested way to replace a service by a newer version consists of updat- ing its containing components which requires a temporary shutdown of the component. Special care must be taken to avoid dangling references to old service instances. As this appears to be an overly expensive strategy, we describe the use of the well-known Bridge design pattern to decouple service replacement from component updates. Instead of registering services only references to instances of automatically generated bridge classes are registered. This solves not only the problem of dangling references but also avoids stopping and starting de- pendent bundles. 1 Introduction The Open Service Gateway Initiative (OSGi)[1] is a consortium that has specified a JavaTM component framework[2] for delivering, activating, and replacing services over wide-area networks to local-area networks and devices. Since OSGi server im- plementations can be quite small, it is a good candidate when looking for supporting runtime evolution in embedded systems. OSGi components interact by sharing so-called service objects. Services are reg- istered by one component and referenced by others. A major problem of OSGi com- ponent exchange at runtime is the replacement of service objects. Shutting down all dependent components and restarting the replaced sub-system, as recommended by OSGi, seems overly expensive. In this paper, we describe the use of the well-known Bridge design pattern to decouple service replacement from bundle updates.
    [Show full text]
  • Objectives: Interfaces [From Sun's Java Tutorial] Interfaces in Java
    Chulalongkorn University Name _____________________ International School of Engineering Student ID _________________ Department of Computer Engineering Station No. _________________ 2140105 Computer Programming Lab. Date ______________________ Lab 9 – OO Concept (Episode III) Objectives: • Understand the concept of interface • Understand interfaces in Java • Be able to define a class that implements an interface. Interfaces [from Sun’s Java Tutorial] There are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts. For example, imagine a futuristic society where computer‐controlled robotic cars transport passengers through city streets without a human operator. Automobile manufacturers write software (Java, of course) that operates the automobile—stop, start, accelerate, turn left, and so forth. Another industrial group, electronic guidance instrument manufacturers, makes computer systems that receive GPS (Global Positioning Satellite) position data and wireless transmission of traffic conditions and use that information to drive the car. The auto manufacturers must publish an industry‐standard interface that spells out in detail what methods can be invoked to make the car move (any car, from any manufacturer). The guidance manufacturers can then write software that invokes the methods described in the interface to command the car. Neither industrial group needs to know how the other group's software is implemented. In fact, each group considers its software highly proprietary and reserves the right to modify it at any time, as long as it continues to adhere to the published interface.
    [Show full text]
  • Collections and Inheritance
    COMP 401 Prasun Dewan1 Collections and Inheritance In the previous chapter, we defined logical structures with fixed number of nodes. In this chapter, we will see how we can use arrays to define types with a dynamic number of components. The collectiom examples will motivate the main topic of this chapter – inheritance. Inheritance in an object-oriented language is not much different than inheritance in the real world. Just it is possible to automatically inherit money from a benefactor or genes from ancestors, it is possible to inherit code from an object type – specifically the methods and variables defined by that type. The idea of inheritance is related to the IS-A relation. Again, this relation is used in the non-computer world. A human is a mammal; a salmon is a fish; and each of you is a student. Similarly, we say that ACartesianPointy is a Point because it implements Point. We will see that inheritance, like interface implementation, is also an is-a relation. We will show how type checking of object variables is based on this relation. Example Problem To motivate collections, let us consider the problem of implementing the console-based application shown in Figure ???. (replace the figures with actual text for mobile reading) 1 Copyright Prasun Dewan, 2015. Users of this application can enter names, print the set of entered names, and quit the application. A line beginning with q or P is considered a command to quit the application or print the names, respectively. Any other line is considered the entry of a new name.
    [Show full text]
  • Patterns of Interface-Based Programming
    JOURNAL OF OBJECT TECHNOLOGY Online at http://www.jot.fm. Published by ETH Zurich, Chair of Software Engineering ©JOT, 2005 Vol. 4, No. 5, July-August 2005 Patterns of Interface-Based Programming Friedrich Steimann, Universität Hannover Philip Mayer, Universität Hannover Abstract Modern software architectures heavily promote the use of interfaces. Originally conceived as a means to separate specification from implementation, popular programming languages toady accommodate interfaces as special kinds of types that can be used – in place of classes – in variable declarations. While it is clear that these interfaces offer polymorphism independent of the inheritance hierarchy, little has been said about the systematic use of interfaces, or how they are actually used in practice. By providing a set of basic patterns of interface use together with numbers of their frequency we provide insights that should be of interest not only to the practising programmer, but also to the designers and analysts of large code bases. 1 INTRODUCTION After the hype has gone, what remains from a new technology is often not what it has originally been acclaimed for. In the case of object-oriented programming, it seems that the praise for its potential of code reuse through implementation inheritance has vanished in favour of an appreciation of what is sometimes called interface inheritance or, more generally, interface-based programming [Pattison00]. This programming style derives from the fact that instances of different classes are allowed to take the same place (i.e., can be assigned to the same variable) as long as they guarantee to conform to the same interface specification, and that this substitutability is independent from whether or not the classes share implementation.
    [Show full text]
  • Serialization?
    SSeerriiaalliizzaattiioonn 1 Topics ● What is Serialization? ● What is preserved when an object is serialized? ● Transient keyword ● Process of serialization ● Process of deserialization ● Version control ● Changing the default protocol ● Creating your own protocol via Externalizable 2 WWhhaatt iiss SSeerriiaalliizzaattiioonn?? 3 What is Serialization? ● Ability to read or write an object to a stream – Process of "flattening" an object ● Used to save object to some permanent storage – Its state should be written in a serialized form to a file such that the object can be reconstructed at a later time from that file ● Used to pass on to another object via the OutputStream class – Can be sent over the network 4 Streams Used for Serialization ● ObjectOutputStream – For serializing (flattening an object) ● ObjectInputStream – For deserializing (reconstructing an object) 5 Requirement for Serialization ● To allow an object to be serializable: – Its class should implement the Serializable interface ● Serializable interface is marker interface – Its class should also provide a default constructor (a constructor with no arguments) ● Serializability is inherited – Don't have to implement Serializable on every class – Can just implement Serializable once along the class hierarchy 6 Non-Serializable Objects ● Most Java classes are serializable ● Objects of some system-level classes are not serializable – Because the data they represent constantly changes ● Reconstructed object will contain different value anyway ● For example, thread running in my
    [Show full text]