SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Java Generics
Handled By
Dr.T.Abirami
Associate Professor
Department of IT
Kongu Engineering College Perundurai
Generics
• Generics means parameterized data types.
• The idea is to allow data type (Integer, String,
… etc, and user-defined types) to be a
parameter to methods, classes, and interfaces.
• Using Generics, it is possible to create classes
that work with different data types.
generics
• JDK 5 introduces generics, which
supports abstraction over
types (or parameterized types) on classes and
methods.
• The class or method designers can be generic
about types in the definition, while the users are
to provide the specific types (actual type) during
the object instantiation or method invocation.
• The primary usage of generics is to abstract over
types for the Collection Framework.
• Auto-Boxing/Unboxing between Primitives and
their Wrapper Objects
Generics
• Generics helps to create classes, interfaces, and
methods that can be used with different types of
objects (data). Hence, allows us to reuse our
code.
• Note: Generics does not work with primitive
types (int, float, char, etc).
• Generics is used in Java, we can use the ArrayList
class of the Java collections framework.
• ArrayList class is an example of a generics class.
We can use ArrayList to store data of any type.
Generic Programming
• Generics helps to create classes, interfaces,
and methods that can be used with different
data types of objects (data). Hence, allows us
to reuse our code.
• Note: Generics does not work with primitive
types (int, float, char, etc).
Advantages
• Type-safety : We can hold only a single type of
objects in generics. It doesn’t allow to store other
objects.
• Type casting is not required: There is no need to
typecast the object.
• Compile-Time Checking: It is checked at compile
time so problem will not occur at runtime. The
good programming strategy says it is far better to
handle the problem at compile time than
runtime.
Types of Java Generics
• Generic Type Class
• Generic Interface
• Generic Method
• Generic Constructor
Syntax for generics
Class classname <data_type_variable>
{ }
Generic class:
Generic method:
class Demo
{
<data_type_ variable> return_ data _type method_name ()
{
}
}
Generic Class
• A class is said to be Generic if it declares one or
more type variables. These variable types are
known as the type parameters of the Java Class.
• we use <> to specify parameter types in generic
class creation.
• Generics Work Only with Objects
Syntax for creating an Object of a Generic type
Class_name <data type> reference_name = new
Class_name<data type> ();
(OR)
Class_name <data type> reference_name = new
Class_name<>();
Generic Class
example
class Test<T>
{ T a;
T b;
Test(T x, T y)
{
a=x;
b=y;
}
}
public class Main
{
public static void main(String[] args) {
Test<Integer> obj=new Test<Integer>(2,3);
System.out.println(obj.a+obj.b);
}
}
//addition of two numbers using generic class
class Test <T>
{ T a;
T b;
//generic cons....
Test(T x, T y)
{
a=x;
b=y;
}
//generic method
T get()
{
return a;
}
}
class Main {
public static void main(String[] args) {
Test<Integer> obj = new Test<Integer>(34,23);
System.out.println(obj.a+obj.b);
System.out.println(obj.get());
Test<Float> obj1 = new Test<Float>(34.1f,23.3f);
System.out.println(obj1.a+obj1.b);
System.out.println(obj1.get());
}
}
class Main {
public static void main(String[] args) {
// initialize generic class with Integer data
GenericsClass<Integer> intObj = new GenericsClass<>(5);
System.out.println("Generic Class returns: " + intObj.getData());
// initialize generic class with String data
GenericsClass<String> stringObj = new GenericsClass<>("Java Programming");
System.out.println("Generic Class returns: " + stringObj.getData());
}
} class GenericsClass<T> {
// variable of T type
private T data;
public GenericsClass(T data) {
this.data = data;
}
// method that return T type variable
public T getData() {
return this.data;
}
}
Output
Generic Class returns: 5
Generic Class returns:
Java Programing
• T indicates the type parameter. Inside the
Main class, we have created objects of
GenericsClass named intObj and stringObj.
• While creating intObj, the type parameter T is
replaced by Integer. This means intObj uses
the GenericsClass to work with integer data.
• While creating stringObj, the type parameter T
is replaced by String. This means stringObj
uses the GenericsClass to work with string
data.
Generics Methods Rules
• In passing arguments into methods, You place the arguments inside
the round bracket () and pass them into the method.
• In generics, instead of passing arguments, we pass type
information inside the angle brackets <>.
• All generic method declarations have a data type parameter section
by angle parameter
Example: <E>
• Each type parameter section contains one or more type parameters
separated by commas
• Example: <E1,T> void disp(E1 a, T b)
Syntax:
<type-parameter> return_type method_name (parameters) {...}
public class TestGenerics4{
public static < E > void printArray(E[] elements) {
for ( E element : elements){
System.out.println(element );
}
System.out.println();
}
public static void main( String args[] ) {
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'J', 'A', 'V', 'A', 'T','P','O','I','N','T' };
System.out.println( "Printing Integer Array" );
printArray( intArray );
System.out.println( "Printing Character Array" );
printArray( charArray );
}
}
For-each Loop
Syntax:
for(data_type variable : array | collection)
{
//body of for-each loop
}
Example:
class ForEachExample1{
public static void main(String args[]){
//declaring an array
int arr[]={12,13,14,44};
//traversing the array with for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
Generics Methods
class Main {
public static void main(String[] args) {
// initialize the class with Integer data
DemoClass demo = new DemoClass();
demo.<String>genericsMethod("Java Programming");
}
}
class DemoClass {
// generics method
public <T> void genericsMethod(T data) {
System.out.println("This is a generics method.");
System.out.println("The data passed to method is " + data);
}
}
• public <T> void genericMethod(T data) {...} Here,
the type parameter <T> is inserted after the
modifier (public) and before the return type
(void).
• We can call the generics method by placing the
actual type <String> inside the bracket before the
method name.
• demo.<String>genericMethod("Java
Programming"); Note: In most cases, we can omit
the type parameter while calling the generics
method. It is because the compiler can match the
type parameter using the value passed to the
method. For example,
• demo.genericsMethod("Java Programming");
Generic Constructor
class sample
{
Object a;
<T> sample(T b)
{
a=b;
}
void disp(){
System.out.println(a);
}
}
public class Generic1 {
public static void main(String ar[]){
sample s=new sample(“Hi");
sample s=new sample(‘A’);
sample s=new sample(4);
sample s=new sample(5.4);
s.disp();
}
}
Generic Constructor
class sample
{
<T> sample(T x,T y)
{
System.out.println(x);
System.out.println(y);
}
}
public class Generic2 {
public static void main(String ar[]){
sample s=new sample(2,4);
}
}
Generic Type with more than one parameter
public class Generic4 {
<E,T> void disp(E a, T b){
System.out.println(a);
System.out.println(b);
}
public static void main(String ar[]){
Generic4 g=new Generic4();
g.disp(4,6.5);
g.disp(4.5,5);
}
}
Generic Method
Generic Method
class sample{
< E > void printArray(E[] elements) {
for ( E element : elements){
System.out.println(element );
}
}
}
public class Generic3{
public static void main( String args[] ) {
sample s=new sample();
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'E', 'N', 'G', 'I', 'N','E','E','R','I','N','G' };
System.out.println( "Printing Integer Array" );
s.printArray(intArray);
System.out.println( "Printing Character Array" );
s.printArray(charArray);
}
}
class sample<G>
{
G obj;
sample(G a){
obj=a;
}
void disp(){
System.out.println(obj);
}
}
public class Generic7{
public static void main(String ar[]){
sample <Integer> s=new sample<Integer>(15);
s.disp();
sample <String> s1=new sample<String>(“Fox");
s1.disp();
}
Generic Class
class sample<G, T>{
G obj1;
T obj2;
sample(G a, T b){
obj1=a;
obj2=b;
}
void disp(){
System.out.println(obj1+" "+obj2);
}
}
public class Generic8{
public static void main(String ar[]){
sample <Integer, String> s=new sample<Integer, String> (15,“Kongu");
s.disp();
sample <String,Integer> s1=new sample<String,Integer>(“Kongu
eng",20);
s1.disp();
Generic Class
class twogen<T,V>{
T obj1;
V obj2;
twogen(T o1,V o2) {
obj1=o1;
obj2=o2;
}
T getobj1() {
return obj1;
}
V getobj2() {
return obj2;
}
void showType() {
System.out.println("type is" + obj1.getClass().getName());
System.out.println("type is" + obj2.getClass().getName());
}}
public class Generic11{
public static void main(String args[]) {
twogen<Integer,String> tobj=new twogen<Integer,String>(99,"kec");
tobj.showType();
int v=tobj.getobj1();
String u=tobj.getobj2();
System.out.println("u="+u+" "+"v="+v);
}}
Generic Class
Ans:
type isjava.lang.Integer
type isjava.lang.String
u=kec v=99
class constructors{
<T extends Number>int showval(T a, T b){
return (a.intValue()+b.intValue());
}}
class Generic15{
public static void main(String r[]){
constructors s=new constructors();
int sum=s.showval(10,20);
System.out.println(sum);
}}
Generic Type addition
class constructors{
int a;
<T extends Number>constructors(T x){
a=x.intValue();
}
void showval(int b){
int sum=a+b;
System.out.println("sum:"+sum);
}}
class Generic14{
public static void main(String r[]){
constructors s1=new constructors(10);
constructors s2=new constructors(12.3F);
s1.showval(9);
s2.showval(10);
}}
Generic Type
addition
class sample
{
static <T extends Number>
void add (T a, T b)
{
System.out.println(b.doubleValue()+a.doubleValue());
}
public static void main(String aa[])
{
Integer a=8, b=10;
add(a,b);
Float c=12.5f,d=45.5f;
add(c,d);
Double e=12.5,f=45.5;
add(e,f);
}}
Generic Type addition
Generic Interface
interface I1<T>
{
void disp(T a);
}
class sample <T>implements I1<T>
{
public void disp(T a)
{
System.out.println(a);
}}
public class Generic5 {
public static void main(String ar[])
{
sample <Integer>s=new sample<Integer>();
s.disp(5);
sample <Double>s1=new sample<Double>();
s1.disp(5.4);
If we using 2 parameter in the
inherited class
class sam <T,U> implements I1<T>
class sample1<T>{
void disp(T a){
System.out.println(a);
}
}
class sample2<T> extends sample1<T>{
void disp(T a){
System.out.println("Derived"+a);
}
}
public class Generic10 {
public static void main(String ar[]){
sample1<Integer> s1=new sample1<Integer>();
s1.disp(4);
sample1<Double> s2=new sample2<Double>();
s2.disp(5.2);
}
}
class general{
int num;
general(int i){
num=i;
}
int get(){
return num;
}}
class Gen<T>extends general{
T obj;
Gen(T o,int i){
super(i);
obj=o;
}
T getobj(){
return obj;
}
void show(){
System.out.println("base class...");
}}
Generic Class Hierarchies
Contd…
class gen2<T,V> extends Gen<T>{
V obj1;
gen2(T o, V s,int i){
super(o,i);
obj1=s;
}
V getobj2(){
return obj1;
}
void show(){
super.show();
System.out.println("subclass...");
}}
public class Generic16{
public static void main(String r[]) {
gen2<Integer,String> is=new gen2<Integer,String>(100,"java",100);
System.out.println("String:"+is.getobj2());
System.out.println("value:"+is.getobj());
System.out.println("nongeneric value:"+is.get());
is.show();
}}
Generic Class Hierarchies
Wildcards in Java
• The ? (question mark) symbol represents the
wildcard element.
• It means any type.
• If we write <? extends Number>, it means any
child class of Number, e.g., Integer, Float, and
double.
• Now we can call the method of Number class
through any child class object.
Wildcards in Java
• The question mark (?) is known as the wildcard
in generic programming .
• It represents an unknown type.
• We can use a wildcard as a type of a parameter,
field, return type, or local variable.
• However, it is not allowed to use a wildcard as a
type argument for a generic method invocation,
a generic class instance creation, or a
supertype.
class Gen<T>{
T obj;
Gen(T o) {
obj=o;
}
T getobj() {
return obj;
}}
class rawtype{
public static void main(String r[]){
Gen<Integer>o1=new Gen<Integer>(100);
Gen<String>o2=new Gen<String>("java");
//int v=o1.getobj();
System.out.println("Value:"+o1.getobj());
//String s=o2.getobj();
System.out.println("String:"+o2.getobj());
Gen raw=new Gen(new Double(100.0));
double d=(Double)raw.getobj();
System.out.println("raw value:"+d);

Weitere ähnliche Inhalte

Was ist angesagt?

5 collection framework
5 collection framework5 collection framework
5 collection frameworkMinal Maniar
 
Java collections concept
Java collections conceptJava collections concept
Java collections conceptkumar gaurav
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets Hitesh-Java
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections TutorialsProf. Erwin Globio
 
07 java collection
07 java collection07 java collection
07 java collectionAbhishek Khune
 
Collections in Java
Collections in JavaCollections in Java
Collections in JavaKhasim Cise
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection frameworkankitgarg_er
 
java collections
java collectionsjava collections
java collectionsjaveed_mhd
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & setsRatnaJava
 
Collection framework
Collection frameworkCollection framework
Collection frameworkRavi_Kant_Sahu
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - JavaDrishti Bhalla
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in javaCPD INDIA
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List Hitesh-Java
 
Collections Java e Google Collections
Collections Java e Google CollectionsCollections Java e Google Collections
Collections Java e Google CollectionsAndrĂŠ Faria Gomes
 
Java Collections
Java CollectionsJava Collections
Java Collectionsparag
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structuresagorolabs
 
collection framework in java
collection framework in javacollection framework in java
collection framework in javaMANOJ KUMAR
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in javayugandhar vadlamudi
 
Java collections
Java collectionsJava collections
Java collectionsAmar Kutwal
 

Was ist angesagt? (20)

5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
07 java collection
07 java collection07 java collection
07 java collection
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
java collections
java collectionsjava collections
java collections
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Collections Java e Google Collections
Collections Java e Google CollectionsCollections Java e Google Collections
Collections Java e Google Collections
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Java collections
Java collectionsJava collections
Java collections
 

Ähnlich wie Generics

GenericsFinal.ppt
GenericsFinal.pptGenericsFinal.ppt
GenericsFinal.pptVirat10366
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Generic programming in java
Generic programming in javaGeneric programming in java
Generic programming in javaanshu_atri
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Andrew Petryk
 
Chap1 array
Chap1 arrayChap1 array
Chap1 arrayraksharao
 
java training faridabad
java training faridabadjava training faridabad
java training faridabadWoxa Technologies
 
core java
 core java core java
core javadssreenath
 
object oriented programming java lectures
object oriented programming java lecturesobject oriented programming java lectures
object oriented programming java lecturesMSohaib24
 
arrays in c# including Classes handling arrays
arrays in c#  including Classes handling arraysarrays in c#  including Classes handling arrays
arrays in c# including Classes handling arraysJayanthiM19
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIjagriti srivastava
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
 
Jdk1.5 Features
Jdk1.5 FeaturesJdk1.5 Features
Jdk1.5 Featuresindia_mani
 

Ähnlich wie Generics (20)

GenericsFinal.ppt
GenericsFinal.pptGenericsFinal.ppt
GenericsFinal.ppt
 
Java introduction
Java introductionJava introduction
Java introduction
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Generic programming in java
Generic programming in javaGeneric programming in java
Generic programming in java
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 
final year project center in Coimbatore
final year project center in Coimbatorefinal year project center in Coimbatore
final year project center in Coimbatore
 
Chap1 array
Chap1 arrayChap1 array
Chap1 array
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
 
core java
 core java core java
core java
 
object oriented programming java lectures
object oriented programming java lecturesobject oriented programming java lectures
object oriented programming java lectures
 
arrays in c# including Classes handling arrays
arrays in c#  including Classes handling arraysarrays in c#  including Classes handling arrays
arrays in c# including Classes handling arrays
 
Templates
TemplatesTemplates
Templates
 
Java
Java Java
Java
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
Jdk1.5 Features
Jdk1.5 FeaturesJdk1.5 Features
Jdk1.5 Features
 

Mehr von Kongu Engineering College, Perundurai, Erode

A REST API (also called a RESTful API or RESTful web API) is an application p...
A REST API (also called a RESTful API or RESTful web API) is an application p...A REST API (also called a RESTful API or RESTful web API) is an application p...
A REST API (also called a RESTful API or RESTful web API) is an application p...Kongu Engineering College, Perundurai, Erode
 
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...Kongu Engineering College, Perundurai, Erode
 

Mehr von Kongu Engineering College, Perundurai, Erode (20)

Introduction to Spring & Spring BootFramework
Introduction to Spring  & Spring BootFrameworkIntroduction to Spring  & Spring BootFramework
Introduction to Spring & Spring BootFramework
 
A REST API (also called a RESTful API or RESTful web API) is an application p...
A REST API (also called a RESTful API or RESTful web API) is an application p...A REST API (also called a RESTful API or RESTful web API) is an application p...
A REST API (also called a RESTful API or RESTful web API) is an application p...
 
SOA and Monolith Architecture - Micro Services.pptx
SOA and Monolith Architecture - Micro Services.pptxSOA and Monolith Architecture - Micro Services.pptx
SOA and Monolith Architecture - Micro Services.pptx
 
Application Layer.pptx
Application Layer.pptxApplication Layer.pptx
Application Layer.pptx
 
Connect to NoSQL Database using Node JS.pptx
Connect to NoSQL Database using Node JS.pptxConnect to NoSQL Database using Node JS.pptx
Connect to NoSQL Database using Node JS.pptx
 
Node_basics.pptx
Node_basics.pptxNode_basics.pptx
Node_basics.pptx
 
Navigation Bar.pptx
Navigation Bar.pptxNavigation Bar.pptx
Navigation Bar.pptx
 
Bootstarp installation.pptx
Bootstarp installation.pptxBootstarp installation.pptx
Bootstarp installation.pptx
 
nested_Object as Parameter & Recursion_Later_commamd.pptx
nested_Object as Parameter  & Recursion_Later_commamd.pptxnested_Object as Parameter  & Recursion_Later_commamd.pptx
nested_Object as Parameter & Recursion_Later_commamd.pptx
 
Chapter 3.pdf
Chapter 3.pdfChapter 3.pdf
Chapter 3.pdf
 
Introduction to Social Media and Social Networks.pdf
Introduction to Social Media and Social Networks.pdfIntroduction to Social Media and Social Networks.pdf
Introduction to Social Media and Social Networks.pdf
 
Dropdown Menu or Combo List.pdf
Dropdown Menu or Combo List.pdfDropdown Menu or Combo List.pdf
Dropdown Menu or Combo List.pdf
 
div tag.pdf
div tag.pdfdiv tag.pdf
div tag.pdf
 
Dimensions of elements.pdf
Dimensions of elements.pdfDimensions of elements.pdf
Dimensions of elements.pdf
 
CSS Positioning Elements.pdf
CSS Positioning Elements.pdfCSS Positioning Elements.pdf
CSS Positioning Elements.pdf
 
Random number generation_upload.pdf
Random number generation_upload.pdfRandom number generation_upload.pdf
Random number generation_upload.pdf
 
JavaScript_introduction_upload.pdf
JavaScript_introduction_upload.pdfJavaScript_introduction_upload.pdf
JavaScript_introduction_upload.pdf
 
Computer Networks: Quality of service
Computer Networks: Quality of serviceComputer Networks: Quality of service
Computer Networks: Quality of service
 
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...
 
Transport layer services
Transport layer servicesTransport layer services
Transport layer services
 

KĂźrzlich hochgeladen

main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
An introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxAn introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxPurva Nikam
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction managementMariconPadriquez1
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Comparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization TechniquesComparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization Techniquesugginaramesh
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncssuser2ae721
 

KĂźrzlich hochgeladen (20)

POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
An introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxAn introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptx
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction management
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Comparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization TechniquesComparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization Techniques
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
 

Generics

  • 1. Java Generics Handled By Dr.T.Abirami Associate Professor Department of IT Kongu Engineering College Perundurai
  • 2. Generics • Generics means parameterized data types. • The idea is to allow data type (Integer, String, … etc, and user-defined types) to be a parameter to methods, classes, and interfaces. • Using Generics, it is possible to create classes that work with different data types.
  • 3. generics • JDK 5 introduces generics, which supports abstraction over types (or parameterized types) on classes and methods. • The class or method designers can be generic about types in the definition, while the users are to provide the specific types (actual type) during the object instantiation or method invocation.
  • 4. • The primary usage of generics is to abstract over types for the Collection Framework. • Auto-Boxing/Unboxing between Primitives and their Wrapper Objects
  • 5. Generics • Generics helps to create classes, interfaces, and methods that can be used with different types of objects (data). Hence, allows us to reuse our code. • Note: Generics does not work with primitive types (int, float, char, etc). • Generics is used in Java, we can use the ArrayList class of the Java collections framework. • ArrayList class is an example of a generics class. We can use ArrayList to store data of any type.
  • 6. Generic Programming • Generics helps to create classes, interfaces, and methods that can be used with different data types of objects (data). Hence, allows us to reuse our code. • Note: Generics does not work with primitive types (int, float, char, etc).
  • 7. Advantages • Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store other objects. • Type casting is not required: There is no need to typecast the object. • Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good programming strategy says it is far better to handle the problem at compile time than runtime.
  • 8. Types of Java Generics • Generic Type Class • Generic Interface • Generic Method • Generic Constructor
  • 9. Syntax for generics Class classname <data_type_variable> { } Generic class: Generic method: class Demo { <data_type_ variable> return_ data _type method_name () { } }
  • 10. Generic Class • A class is said to be Generic if it declares one or more type variables. These variable types are known as the type parameters of the Java Class. • we use <> to specify parameter types in generic class creation. • Generics Work Only with Objects
  • 11. Syntax for creating an Object of a Generic type Class_name <data type> reference_name = new Class_name<data type> (); (OR) Class_name <data type> reference_name = new Class_name<>(); Generic Class
  • 12. example class Test<T> { T a; T b; Test(T x, T y) { a=x; b=y; } } public class Main { public static void main(String[] args) { Test<Integer> obj=new Test<Integer>(2,3); System.out.println(obj.a+obj.b); } }
  • 13. //addition of two numbers using generic class class Test <T> { T a; T b; //generic cons.... Test(T x, T y) { a=x; b=y; } //generic method T get() { return a; } } class Main { public static void main(String[] args) { Test<Integer> obj = new Test<Integer>(34,23); System.out.println(obj.a+obj.b); System.out.println(obj.get()); Test<Float> obj1 = new Test<Float>(34.1f,23.3f); System.out.println(obj1.a+obj1.b); System.out.println(obj1.get()); } }
  • 14. class Main { public static void main(String[] args) { // initialize generic class with Integer data GenericsClass<Integer> intObj = new GenericsClass<>(5); System.out.println("Generic Class returns: " + intObj.getData()); // initialize generic class with String data GenericsClass<String> stringObj = new GenericsClass<>("Java Programming"); System.out.println("Generic Class returns: " + stringObj.getData()); } } class GenericsClass<T> { // variable of T type private T data; public GenericsClass(T data) { this.data = data; } // method that return T type variable public T getData() { return this.data; } } Output Generic Class returns: 5 Generic Class returns: Java Programing
  • 15. • T indicates the type parameter. Inside the Main class, we have created objects of GenericsClass named intObj and stringObj. • While creating intObj, the type parameter T is replaced by Integer. This means intObj uses the GenericsClass to work with integer data. • While creating stringObj, the type parameter T is replaced by String. This means stringObj uses the GenericsClass to work with string data.
  • 16. Generics Methods Rules • In passing arguments into methods, You place the arguments inside the round bracket () and pass them into the method. • In generics, instead of passing arguments, we pass type information inside the angle brackets <>. • All generic method declarations have a data type parameter section by angle parameter Example: <E> • Each type parameter section contains one or more type parameters separated by commas • Example: <E1,T> void disp(E1 a, T b) Syntax: <type-parameter> return_type method_name (parameters) {...}
  • 17. public class TestGenerics4{ public static < E > void printArray(E[] elements) { for ( E element : elements){ System.out.println(element ); } System.out.println(); } public static void main( String args[] ) { Integer[] intArray = { 10, 20, 30, 40, 50 }; Character[] charArray = { 'J', 'A', 'V', 'A', 'T','P','O','I','N','T' }; System.out.println( "Printing Integer Array" ); printArray( intArray ); System.out.println( "Printing Character Array" ); printArray( charArray ); } }
  • 18. For-each Loop Syntax: for(data_type variable : array | collection) { //body of for-each loop } Example: class ForEachExample1{ public static void main(String args[]){ //declaring an array int arr[]={12,13,14,44}; //traversing the array with for-each loop for(int i:arr){ System.out.println(i); } } }
  • 19. Generics Methods class Main { public static void main(String[] args) { // initialize the class with Integer data DemoClass demo = new DemoClass(); demo.<String>genericsMethod("Java Programming"); } } class DemoClass { // generics method public <T> void genericsMethod(T data) { System.out.println("This is a generics method."); System.out.println("The data passed to method is " + data); } }
  • 20. • public <T> void genericMethod(T data) {...} Here, the type parameter <T> is inserted after the modifier (public) and before the return type (void). • We can call the generics method by placing the actual type <String> inside the bracket before the method name. • demo.<String>genericMethod("Java Programming"); Note: In most cases, we can omit the type parameter while calling the generics method. It is because the compiler can match the type parameter using the value passed to the method. For example, • demo.genericsMethod("Java Programming");
  • 21. Generic Constructor class sample { Object a; <T> sample(T b) { a=b; } void disp(){ System.out.println(a); } } public class Generic1 { public static void main(String ar[]){ sample s=new sample(“Hi"); sample s=new sample(‘A’); sample s=new sample(4); sample s=new sample(5.4); s.disp(); } }
  • 22. Generic Constructor class sample { <T> sample(T x,T y) { System.out.println(x); System.out.println(y); } } public class Generic2 { public static void main(String ar[]){ sample s=new sample(2,4); } } Generic Type with more than one parameter
  • 23. public class Generic4 { <E,T> void disp(E a, T b){ System.out.println(a); System.out.println(b); } public static void main(String ar[]){ Generic4 g=new Generic4(); g.disp(4,6.5); g.disp(4.5,5); } } Generic Method
  • 24. Generic Method class sample{ < E > void printArray(E[] elements) { for ( E element : elements){ System.out.println(element ); } } } public class Generic3{ public static void main( String args[] ) { sample s=new sample(); Integer[] intArray = { 10, 20, 30, 40, 50 }; Character[] charArray = { 'E', 'N', 'G', 'I', 'N','E','E','R','I','N','G' }; System.out.println( "Printing Integer Array" ); s.printArray(intArray); System.out.println( "Printing Character Array" ); s.printArray(charArray); } }
  • 25. class sample<G> { G obj; sample(G a){ obj=a; } void disp(){ System.out.println(obj); } } public class Generic7{ public static void main(String ar[]){ sample <Integer> s=new sample<Integer>(15); s.disp(); sample <String> s1=new sample<String>(“Fox"); s1.disp(); } Generic Class
  • 26. class sample<G, T>{ G obj1; T obj2; sample(G a, T b){ obj1=a; obj2=b; } void disp(){ System.out.println(obj1+" "+obj2); } } public class Generic8{ public static void main(String ar[]){ sample <Integer, String> s=new sample<Integer, String> (15,“Kongu"); s.disp(); sample <String,Integer> s1=new sample<String,Integer>(“Kongu eng",20); s1.disp(); Generic Class
  • 27. class twogen<T,V>{ T obj1; V obj2; twogen(T o1,V o2) { obj1=o1; obj2=o2; } T getobj1() { return obj1; } V getobj2() { return obj2; } void showType() { System.out.println("type is" + obj1.getClass().getName()); System.out.println("type is" + obj2.getClass().getName()); }} public class Generic11{ public static void main(String args[]) { twogen<Integer,String> tobj=new twogen<Integer,String>(99,"kec"); tobj.showType(); int v=tobj.getobj1(); String u=tobj.getobj2(); System.out.println("u="+u+" "+"v="+v); }} Generic Class Ans: type isjava.lang.Integer type isjava.lang.String u=kec v=99
  • 28. class constructors{ <T extends Number>int showval(T a, T b){ return (a.intValue()+b.intValue()); }} class Generic15{ public static void main(String r[]){ constructors s=new constructors(); int sum=s.showval(10,20); System.out.println(sum); }} Generic Type addition
  • 29. class constructors{ int a; <T extends Number>constructors(T x){ a=x.intValue(); } void showval(int b){ int sum=a+b; System.out.println("sum:"+sum); }} class Generic14{ public static void main(String r[]){ constructors s1=new constructors(10); constructors s2=new constructors(12.3F); s1.showval(9); s2.showval(10); }} Generic Type addition
  • 30. class sample { static <T extends Number> void add (T a, T b) { System.out.println(b.doubleValue()+a.doubleValue()); } public static void main(String aa[]) { Integer a=8, b=10; add(a,b); Float c=12.5f,d=45.5f; add(c,d); Double e=12.5,f=45.5; add(e,f); }} Generic Type addition
  • 31. Generic Interface interface I1<T> { void disp(T a); } class sample <T>implements I1<T> { public void disp(T a) { System.out.println(a); }} public class Generic5 { public static void main(String ar[]) { sample <Integer>s=new sample<Integer>(); s.disp(5); sample <Double>s1=new sample<Double>(); s1.disp(5.4); If we using 2 parameter in the inherited class class sam <T,U> implements I1<T>
  • 32. class sample1<T>{ void disp(T a){ System.out.println(a); } } class sample2<T> extends sample1<T>{ void disp(T a){ System.out.println("Derived"+a); } } public class Generic10 { public static void main(String ar[]){ sample1<Integer> s1=new sample1<Integer>(); s1.disp(4); sample1<Double> s2=new sample2<Double>(); s2.disp(5.2); } }
  • 33. class general{ int num; general(int i){ num=i; } int get(){ return num; }} class Gen<T>extends general{ T obj; Gen(T o,int i){ super(i); obj=o; } T getobj(){ return obj; } void show(){ System.out.println("base class..."); }} Generic Class Hierarchies Contd…
  • 34. class gen2<T,V> extends Gen<T>{ V obj1; gen2(T o, V s,int i){ super(o,i); obj1=s; } V getobj2(){ return obj1; } void show(){ super.show(); System.out.println("subclass..."); }} public class Generic16{ public static void main(String r[]) { gen2<Integer,String> is=new gen2<Integer,String>(100,"java",100); System.out.println("String:"+is.getobj2()); System.out.println("value:"+is.getobj()); System.out.println("nongeneric value:"+is.get()); is.show(); }} Generic Class Hierarchies
  • 35. Wildcards in Java • The ? (question mark) symbol represents the wildcard element. • It means any type. • If we write <? extends Number>, it means any child class of Number, e.g., Integer, Float, and double. • Now we can call the method of Number class through any child class object.
  • 36. Wildcards in Java • The question mark (?) is known as the wildcard in generic programming . • It represents an unknown type. • We can use a wildcard as a type of a parameter, field, return type, or local variable. • However, it is not allowed to use a wildcard as a type argument for a generic method invocation, a generic class instance creation, or a supertype.
  • 37. class Gen<T>{ T obj; Gen(T o) { obj=o; } T getobj() { return obj; }} class rawtype{ public static void main(String r[]){ Gen<Integer>o1=new Gen<Integer>(100); Gen<String>o2=new Gen<String>("java"); //int v=o1.getobj(); System.out.println("Value:"+o1.getobj()); //String s=o2.getobj(); System.out.println("String:"+o2.getobj()); Gen raw=new Gen(new Double(100.0)); double d=(Double)raw.getobj(); System.out.println("raw value:"+d);