This document provides an overview of Java generics. It discusses what generics are, their history and motivation, how they improved type safety over non-generic collections. Key points covered include the Collections Framework being rewritten using generics, concepts like type erasure and type parameters. It also discusses bounded types, wildcards and examples of generic classes, methods and interfaces.
Just a simple intro to typescript.
Most of the contents are of any OO language, hence slide contents are minimal. If anyone need any further help, reach me out - akhil2369492@gmail.com
-Akhil
Just a simple intro to typescript.
Most of the contents are of any OO language, hence slide contents are minimal. If anyone need any further help, reach me out - akhil2369492@gmail.com
-Akhil
Introduction to TypeScript, demo ( http://goo.gl/VtE4Vm ), Comparison with couple of popular alternatives. (Sadly layout of the slides are a bit ruined by conversion to SlideShare format - original file: http://goo.gl/eeJgbR )
Slide 1
TypeScript
* This presentation is to show TypeScript's major feature and the benefit that it brings to your JavaScript projects.
* Our main objective is just to spark interest especially to those not familiar with the tool.
Slide 2
- What is TypeScript
* go to next slide
Slide 3
- Is a superset of JavaScript
* it simply means an extension to JavaScript
- Use JavaScript code on TypeScript
* JS code naturally works on TypeScript
* Which also means your beloved JavaScript libraries such as JQuery, or your fancy interacive plugins would work as well.
- TypeScript compiles to plain old JavaScript
* TS code compiles to simple and clean JS.
Slide 4
- Screenshot of TS compiled to JS
* In this example, compiling a TS class code would result to a JS version, and a regular JavaScript function when compiled is basically untouched.
Slide 5
- TypeScript's Main Feature
* So what does TS provide us with? What does it actually do?
Slide 6
- Static Type Checking
* TypeScript allows us to enable type checking by defining data types to your for ex. variables, function parameters and return types.
Slide 7
- Screenshot of basic Static Type Checking
* In this example…
* What I've done here was to assign supposedly wrong values for what the variables or parameters were meant to hold
* As JavaScript is a dynamic and untyped language these expressions would either fail or be okay when you run it on your browser.
* In TypeScript by enabling static type checking these potential errors are caught earlier (see the red marks on the expressions) and wouldn't even allow you to compile unless these are resolved.
* In addition you can also type arrays and object literals
Slide 8
- Effects of Static Type Checking
* As TS code is statically type-checked a side effect of such...
- Allows IDEs to perform live error checks
- Exposes auto-completion and code hinting
Slide 9
- Screenshot of code hinting
* Say I was coding JQuery on regular JavaScript code there would be no natural way to help me identify its class properties, methods and parameters... except through reading the API documentation or a separate plugin.
* As a result of static type checking this allows IDE's to access these class members as code hints
* So if this was a 3rd party library how much more if you are just referencing your own JavaScript/TypeScript files within your project.
Slide 10
- A few of the other cool features
* That was only the basic feature of TypeScript
* A few of the other cool features are...
Slide 11
- End
Properties are named members of classes, structures, and interfaces. Member variables or methods in a class or structures are called Fields. Properties are an extension of fields and are accessed using the same syntax. They use accessors through which the values of the private fields can be read, written, or manipulated.
An indexer allows an object to be indexed such as an array. When you define an indexer for a class, this class behaves similar to a virtual array. You can then access the instance of this class using the array access operator ([ ]).
Debugging in JavaScript
It is common to have errors while writing codes and the errors can be due to syntax or logical. These errors create a lot of ambiguity in the logic and understanding of both users and programmers. There can also be errors in the code which can remain invisible to the programmer’s eye and can create havoc. To identify these errors we need Debuggers that can go through the entire code or program, identify the errors and also fix them.
-Debugger
The debugger keyword is used in the code to force stop the execution of the code at a breaking point and calls the debugging function. The debugger function is executed if any debugging is needed at all else no action is performed.
Here I discuss about Java programming language and easiest way to solve programming problem. Java basic syntax and their uses are described briefly so that anyone can easily understand within very short time. If anyone follow the slide with proper way,I assure that he or she will find java programming interesting.
Java is Object Oriented Programming. Java 8 is the latest version of the Java which is used by many companies for the development in many areas. Mobile, Web, Standalone applications.
Introduction to TypeScript, demo ( http://goo.gl/VtE4Vm ), Comparison with couple of popular alternatives. (Sadly layout of the slides are a bit ruined by conversion to SlideShare format - original file: http://goo.gl/eeJgbR )
Slide 1
TypeScript
* This presentation is to show TypeScript's major feature and the benefit that it brings to your JavaScript projects.
* Our main objective is just to spark interest especially to those not familiar with the tool.
Slide 2
- What is TypeScript
* go to next slide
Slide 3
- Is a superset of JavaScript
* it simply means an extension to JavaScript
- Use JavaScript code on TypeScript
* JS code naturally works on TypeScript
* Which also means your beloved JavaScript libraries such as JQuery, or your fancy interacive plugins would work as well.
- TypeScript compiles to plain old JavaScript
* TS code compiles to simple and clean JS.
Slide 4
- Screenshot of TS compiled to JS
* In this example, compiling a TS class code would result to a JS version, and a regular JavaScript function when compiled is basically untouched.
Slide 5
- TypeScript's Main Feature
* So what does TS provide us with? What does it actually do?
Slide 6
- Static Type Checking
* TypeScript allows us to enable type checking by defining data types to your for ex. variables, function parameters and return types.
Slide 7
- Screenshot of basic Static Type Checking
* In this example…
* What I've done here was to assign supposedly wrong values for what the variables or parameters were meant to hold
* As JavaScript is a dynamic and untyped language these expressions would either fail or be okay when you run it on your browser.
* In TypeScript by enabling static type checking these potential errors are caught earlier (see the red marks on the expressions) and wouldn't even allow you to compile unless these are resolved.
* In addition you can also type arrays and object literals
Slide 8
- Effects of Static Type Checking
* As TS code is statically type-checked a side effect of such...
- Allows IDEs to perform live error checks
- Exposes auto-completion and code hinting
Slide 9
- Screenshot of code hinting
* Say I was coding JQuery on regular JavaScript code there would be no natural way to help me identify its class properties, methods and parameters... except through reading the API documentation or a separate plugin.
* As a result of static type checking this allows IDE's to access these class members as code hints
* So if this was a 3rd party library how much more if you are just referencing your own JavaScript/TypeScript files within your project.
Slide 10
- A few of the other cool features
* That was only the basic feature of TypeScript
* A few of the other cool features are...
Slide 11
- End
Properties are named members of classes, structures, and interfaces. Member variables or methods in a class or structures are called Fields. Properties are an extension of fields and are accessed using the same syntax. They use accessors through which the values of the private fields can be read, written, or manipulated.
An indexer allows an object to be indexed such as an array. When you define an indexer for a class, this class behaves similar to a virtual array. You can then access the instance of this class using the array access operator ([ ]).
Debugging in JavaScript
It is common to have errors while writing codes and the errors can be due to syntax or logical. These errors create a lot of ambiguity in the logic and understanding of both users and programmers. There can also be errors in the code which can remain invisible to the programmer’s eye and can create havoc. To identify these errors we need Debuggers that can go through the entire code or program, identify the errors and also fix them.
-Debugger
The debugger keyword is used in the code to force stop the execution of the code at a breaking point and calls the debugging function. The debugger function is executed if any debugging is needed at all else no action is performed.
Here I discuss about Java programming language and easiest way to solve programming problem. Java basic syntax and their uses are described briefly so that anyone can easily understand within very short time. If anyone follow the slide with proper way,I assure that he or she will find java programming interesting.
Java is Object Oriented Programming. Java 8 is the latest version of the Java which is used by many companies for the development in many areas. Mobile, Web, Standalone applications.
This presentation comes with many additional notes (pdf): http://de.slideshare.net/nicolayludwig/4-collections-algorithms-38613530
- Object-based vs. generic Collections
-- Generics Types in Java
- Sequential and associative Collections
- Associative Collections
-- Equivalence-based associative Collections: .Net's SortedDictionary
-- Operations on .Net's IDictionarys
-- Comparison and Implementation of .Net's Interfaces IComparable and IComparer
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptxMarco Parenzan
Did interfaces in C# need evolution? Maybe yes. Are they violating some fundamental principles? We see. Are we asking for some hoops? Let's see all this by telling a story (of code, of course)
Functional programming is getting a lot of attention because it eases many of the difficulties faced in object-oriented programming (OOP) such as testability, maintainability, scalability, and concurrency. Swift has a lot of functional programming features that can be easily used, but most of Objective-C and Swift programmers are not familiar with these concepts.
This talk aims to introduce some of the core concepts of functional programming with Swift such as:
• Importance of Immutability
• First-class, Higher-order and Pure functions
• Closures
• Generics and Associated Type Protocols
• Functors, Applicative Functors and Monads
• Enumerations and Pattern Matching
• Optionals
Presented By:
N.V.Raja Sekhar Reddy
www.technolamp.co.in
Want more interesting...
Watch and Like us @ https://www.facebook.com/Technolamp.co.in
subscribe videos @ http://www.youtube.com/user/nvrajasekhar
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
I have heard many times that architecture is not important for the front-end. Also, many times I have seen how developers implement features on the front-end just following the standard rules for a framework and think that this is enough to successfully launch the project, and then the project fails. How to prevent this and what approach to choose? I have launched dozens of complex projects and during the talk we will analyze which approaches have worked for me and which have not.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
4. Generic History 101
• Generics represent the most significant change
to the Java language since the 1.0 release.
• Over five years in the making, JSR 14 (Generics)
was one of the first Java Specification Requests.
• Generics are desirable because they let you write
code that is safer and easier to read than code
that is littered with Object variables and casts.
• Generic programming is now achieved via type
parameters as opposed to inheritance.
4
5. Life Before Generics
• Generalized classes, interfaces, and methods
were accomplished by operating through
references of type Object.
public Object get(int index);
• Explicit casting was required in order to downcast
Object to whatever concrete implementation
was being represented.
String value = (String) list.get(0);
• Runtime exceptions ran rampant because type
safety could not be guaranteed by the compiler.
5
6. The Generic New World Order
• Generics means parameterized types.
– The type upon which a generic method, class, or
interface operates is specified as a parameter.
• Generics make it possible to create a single
class, for example, that automatically works with
different types of data (Strings, Integers...).
• Type safety is now ensured by the compiler.
– All casts are automatic and implicit.
• Generics expand the ability to write reusable
code and do so in a safe, easy, and inviting
manner.
6
7. Raw Type vs. Generics Example
• Raw type version
List list = new ArrayList();
list.add("1");
String value = (String) list.get(0);
• Generics version
List<String> list = new ArrayList<String>();
list.add("1");
String value = list.get(0);
Note: The term “raw” refers to a generic type used without
actual type arguments. List is the raw type of List<E>.
7
8. Example Continued...
• Raw type version
List list = new ArrayList();
list.add("1");
// Compiler permits
list.add(new Integer(1));
// ClassCastException
String value = (String) list.get(1);
• Generics version
List<String> list = new ArrayList<String>();
list.add("1");
// Compilation error
list.add(new Integer(1));
String value = list.get(1);
8
10. The Collections Framework
• The entire collections framework has been
reworked using generics.
• Raw types provide a means of backward
compatibility (syntactic sugar).
– Under the hood, when a raw type is used, the compiler
actually substitutes the upper bound of each variable
(typically Object) as the actual type argument for that
variable. The following are equivalent…
List list = new ArrayList(); // Raw Type
List<Object> list = new ArrayList<Object>();
10
11. The New & Improved List Interface
public interface List<E> extends Collection<E> {
boolean add(E o);
E get(int index);
Iterator<E> iterator();
}
• E is a type variable or placeholder. It will be
replaced by the actual reference type passed as
an argument to the generic class.
11
12. List Interface Continued...
public interface List<String> extends Collection<String> {
boolean add(String o);
String get(int index);
Iterator<String> iterator();
}
• The type argument, String, replaces all
occurrences of E at runtime.
// String is passed as the parameterized type
List<String> list = new ArrayList<String>();
12
14. Generic Points of Interest
• The compiler generates only one class.
– All invocations share the same generic type.
• Only object reference types can be passed as
type parameters.
– Primitive types cannot be passed as type parameters.
• Generic type parameters are just like ordinary
method parameters. When invoked, the passed
type arguments (String) replace the actual type
parameters (E).
14
15. Points of Interest Continued...
• A reference of one specific version of a generic
type cannot be assigned to a different version of
the same same generic type.
// Wrong! (Same generic, different versions)
listOfStrings = listOfIntegers;
// Wrong! (This one’s tricky. Even though String
// subclasses Object, we can’t be sure listOfObjects
// is only holding Strings)
listOfObjects = listOfStrings;
• Generics are only implemented in the compiler.
– No generic type information is available at runtime due
to erasure.
15
17. The Concept of Erasure
• To ensure backward compatibility, a process
called type erasure is used to map the new
syntax to the current JVM specification.
• Type erasure is the process of translating or
rewriting code that uses generics into non-
generic code.
• When generics are compiled, all generic-specific
information is completely erased.
17
18. Erasure Continued...
• During erasure, all type variables are replaced by
their upper bound or Object if not specified.
// The erasure of T is Number
<T extends Number>
// The erasure of T is Object
<T>
• The compiler adds casts, type conversions, and
synthetic bridge methods as necessary to ensure
type-correct code.
– Bridge methods are inserted into subtypes of
parameterized supertypes to ensure that subtyping
works as expected.
18
19. Erasure Example...
// Pre-Erasure (Notice the type variables)
public void method() {
List<String> list = new ArrayList<String>();
list.add("value");
print(list);
}
// Pre-Erasure (Notice the type variables and omitted cast)
public void print(Collection<String> collection) {
Iterator<String> it = collection.iterator();
while (it.hasNext()) {
String element = it.next();
System.out.println(element);
}
}
19
20. Example Continued...
// Post-Erasure (Erased generics)
public void method() {
List list = new ArrayList();
list.add("value");
print(list);
}
// Post-Erasure (Erased generics and inserted cast)
public void print(Collection collection) {
String s;
for (Iterator it = collection.iterator(); it.hasNext();) {
s = (String) iterator.next();
System.out.println(s);
}
}
20
22. Multiple Type Parameters
• A generic type can accept more than one type
variable. For example, the Map interface accepts
two variables. The first (K) defines the key type
and the second (V) defines the value type.
public interface Map<K,V> {
V put(K key, V value);
V get(Object key);
}
Map<String, String> map = new HashMap<String, String>();
map.put("key", "value");
String value = map.get("key");
22
23. Passing Generics To Generics
• A generic type is itself a type that can be passed
to another generic. Below is how you would
create a list that holds a list of Strings.
List<String> listOfStrings = new ArrayList<String>();
listOfStrings.add("value");
List<List<String>> listOfLists = new ArrayList<List<String>>();
listOfLists.add(listOfStrings);
String value = listOfLists.get(0).get(0);
23
24. Wildcard Arguments
• Wildcards are used to signify an unknown type.
• Syntactically, wildcards are specified with <?>.
// List<?> is the pseudo-supertype of all lists
// It contains a list of unknown types
public void printList(List<?> list) {
// Type variables are always Objects
for (Object element : list) {
System.out.println(element);
}
}
Question: What is the difference between List<?> and List<Object>?
What would happen if we replaced the wildcard with Object?
24
25. Wildcards Continued...
• Wildcard parameterized types are similar to
interfaces...
– They can be declared, but no objects of a wildcard
parameterized type can be created.
// Invalid instantiation attempt of a wildcard
List<?> list = new ArrayList<?>();
– They can refer to an Object that is of a type that
belongs to a family of types the wildcard denotes.
// Valid because Long extends Number (same family)
List<? extends Number> list = new ArrayList<Long>();
// Wrong, String does not extend Number (not related)
List<? extends Number> list = new ArrayList<String>;
25
27. Bounded Types
• Used to restrict what can be passed to a generic
by defining an upper or lower bound of a type
variable.
• Both upper and lower bounds are inclusive.
• Bounds can be either a class or interface.
// The upper bound is an interface
List<? extends Serializable>
// The lower bound is a class
List<? super Integer>
27
28. Upper Bounds
• Upper bounds are defined as follows…
<? extends superclass>
• The extends keyword was chosen because it is
a reasonable approximation of the subtype
concept, and the Java designers didn’t want to
add a new keyword to the language.
• The following accepts a Shape or any subclass
of Shape such as Circle or Square.
// Shape is the upper bound
List<? extends Shape>
28
29. Lower Bounds
• While not as useful, it is also possible to define
the lower bound of a type variable, by using the
super keyword.
<? super subclass>
• The following will take a list of JDialogs or any
object whose class is a superclass of JDialog
such as Dialog or Window.
// JDialog is the lower bound
List<? super JDialog>
29
30. Multiple Bounds
• Type variables can also have multiple bounds.
• Use ampersands to separate bounded types.
<expression... class & interface & interface...>
• As with Java inheritance, there can be multiple
interfaces, but only one class, and it must be the
first bound specified in the list of bounded types.
// Number is the only class and is listed first.
// The interfaces are randomly ordered.
// Notice that T is passed to Comparable<T>.
<T extends Number & Comparable<T> & Serializable>
30
32. Generic Methods
• Methods with type parameters are referred to as
generic methods.
• They can exist within both generic classes and
non-generic classes.
• The scope of a method’s type parameter is
restricted to the method itself.
• Use when dependencies exist among the types
of one or more arguments and/or return type.
// The argument and return type are both of type T
public <T> T[] toArray(T[] a)
32
33. Generic Methods Continued...
• Insert type variables between the modifiers and
return type.
modifiers <typeVariables> returnType methodName(...)
• When calling a generic method, place the type
arguments before the method name.
objectReference.<typeVariables>methodName();
Note: In most cases, you can omit the type parameters from
the method call because the compiler will typically be able
to discern which method based on the actual type
arguments.
33
34. Generic Methods Continued...
public class Collections {
public static <T> void copy(
List<? super T> dest, List<? extends T> src) {
...
}
}
• T is a type variable or placeholder. It will be
replaced by the actual reference type passed as
an argument to the generic method.
Collections.<Dialog>copy(windowList, jDialogList);
Collections.copy(windowList, jDialogList);
34
35. Generic Constructors
• Constructors with type parameters are referred to
as generic constructors .
• They can exist within both generic classes and
non-generic classes.
• The scope of a constructor’s type parameter is
restricted to the constructor itself.
• Use when dependencies exist among the types
of one or more arguments.
• Just as with generic methods, type parameters of
generic constructors need not be provided
explicitly when invoked.
35
37. Custom Generic Classes
• Generic classes use the following syntax…
class className<typeParameters> {
...
}
• Below is the syntax for declaring a reference to a
generic class.
className<typeArguments> variableName =
new className<typeArguments>(constructorArguments);
Note: See GenericExample class.
37
38. Generic Interfaces
• As demonstrated earlier with List and Map,
interfaces can also be generic.
public interface List<E> extends Collection<E> {
boolean addAll(int index, Collection<? extends E> c);
ListIterator<E> listIterator(int index);
E set(int index, E element);
}
• The syntax is the same as with classes…
interface interfaceName<typeParameters> {
...
}
38
39. Generic Class Hierarchies
• The only difference between generic and non-
generic hierarchies is that generic hierarchies
require type variables be passed up the
inheritance tree accordingly.
• There are a few simple rules…
– Generic classes can subclass other generic classes
and non-generic classes.
– Non-generic classes cannot subclass generic classes.
• The reason is that a non-generic subclass cannot receive
type parameters and therefore cannot pass anything to
its generic superclass.
– Subclasses are free to add their own parameters not
required by the generic superclass. 39
40. Generic Restrictions
• Type parameters cannot be instantiated.
// Wrong! (Can’t create an instance of T)
objectReference = new T();
• Static members cannot use a type parameter
declared by the enclosing class.
– However, you can declare static generic methods that
define their own type parameters.
• A generic class cannot extend Throwable. This
means that you cannot create generic exception
classes.
40
41. Restrictions Continued...
• It is not possible to instantiate an array whose
base type is a type parameter.
– The reason is that T does not exist at runtime, so there
is no way for the compiler to know what type of array to
actually create.
public class Generic<T extends Number> {
T[] array;
Generic(T[] numbers) {
array = new T[10]; // Can’t create an array of T
array = numbers; // Reference assignments are fine
}
}
41
42. Restrictions Continued...
• It is also not possible to create an array of type-
specific generic references.
– Arrays of specific generic types simply aren’t allowed
because they can lead to a loss of type safety.
// Wrong! (Type-specific generic references)
Generic<Integer>[] array = new Generic<Integer>[10];
// Okay! (Wildcards are acceptable)
Generic<?>[] array = new Generic<?>[10];
42
44. Converting Legacy To Generics
• Make certain that the generic API is not unduly
restrictive; it must continue to support the original
contract of the API.
• You also need to ensure that the revised API
retains binary compatibility with old clients. This
implies that the erasure of the API must be the
same as the original, ungenerified API. In most
cases, this falls out naturally, but there are some
subtle cases.
44
46. Generics In Context
• Because generics are such a fundamental
change to the language, it’s important to have a
solid understanding of them.
• Most interaction with generics will happen as a
result of using the collections framework.
• For the most part, application developers won’t
write a lot of custom generics, but will use the
generics provided by various frameworks.
• The heavy writing of custom generics seems to
be most applicable for framework development.
46
47. Drawbacks Of Generics
• Steep learning curve
– Generics are a fundamental change and require a
completely different mindset.
– Conceptually, generics can be difficult to grasp and
can lead to code that is difficult to read and follow.
• Added complexity
– Many left C++ because of it’s complexity, some would
argue that Java is headed down that same road.
– Much of Java’s original appeal was its simplicity. Some
believe that the trade-off for type safety is not worth the
added complexity introduced by generics.
47
49. Summary
• Generics are a powerful extension to the Java
language because they streamline the creation of
type-safe, reusable code.
• Within generics, automatic casting and type
converting are provided by the compiler.
• The Collections framework has been entirely
reworked.
– Now collections can be restricted and guaranteed to
only hold the specified type, passed as a parameter.
– The need for type casting when retrieving an element
from a collection has been entirely eliminated.
49
50. Summary Continued...
• Generics provide backward compatibility by
enabling generic types to be used without type
variables (raw types).
– It is strongly recommended; however, that new
applications avoid using raw types as future releases
of Java may not support them (according to the Java
Language Specification).
50