Java Tutorial
IntroductionEnvironment SetupIDEBuild ManagementLanguage SpecificationBasic ProgramVariables Data TypesPackagesModifiersConditionalsLoopsObject OrientedClassesSuperInterfacesEnumStatic importInheritanceAbstractionEncapsulationPolymorphismBoxing & UnboxingConversion Formatting numbers Arrays Command line arguments in java Variable Number of arguments in Java Exception handling in Java String handling in Java StringBuffer and StringBuilder in Java Mathematical Operations in Java Date and Time in Java Regular expressions in Java Input output programming in Java File Handling Nested Classes Collections Generics Serialization Socket programming Multi-Threading Annotations Lambda Expressions Reflections in Java Singleton class in Java Runtime Class in JavaHow to load resource in JavaHow to load properties file in JavaAdvanced
Log4j – Logging framework in JavaInterview Questions in JavaGenerics solves 2 problems –
- Type casting
- Type safety
ArrayList<String> a = new ArrayList<>();
ArrayList<String> a = new ArrayList<>();
package generics;
/**
* Created by ssalunke on 15/04/2016.
*/
/*
Without Generics, we will have to create 2 different Classes
each working with specific Type say Water and Petrol. Here note
that <G> is a type of Parameter.
*/
public class MyGenericClass <G> {
G liquid;
public static void main(String [] args){
MyGenericClass<Water> w = new MyGenericClass<>();
w.liquid = new Water();
MyGenericClass<Petrol> p = new MyGenericClass<>();
p.liquid = new Petrol();
}
}
class Water{
}
class Petrol{
}
Bounded Types in Generics
Bounded types allow us to restrict the types to specific set of classes. For example – Mathematical operations can be performed only on Classes inherited by Number class. So we can restrict the types using extends keyword. In below example, we can create instance of BoundedTypes class using only Number Type or it’s child classes.
package generics;
/**
* Created by ssalunke on 15/04/2016.
*/
//Bounded types are required when we need to work with specific types only
//For example - if we have a generic class that does mathematical operations
//then we should restrict the types using Bounded types
public class BoundedTypes <T extends Number>{
public void add(T a, T b){
System.out.println("Sum of numbers is " + (a.doubleValue()+b.doubleValue()));
}
public void multiply(T a, T b){
System.out.println("Multiplication of numbers is " + (a.doubleValue()*b.doubleValue()));
}
public static void main(String [] args){
BoundedTypes<Integer> intTypes = new BoundedTypes<>();
intTypes.add(11,22);
intTypes.multiply(11,22);
BoundedTypes<Float> floatTypes = new BoundedTypes<>();
floatTypes.add(32.2f,22.4f);
BoundedTypes<Double> doubleTypes = new BoundedTypes<>();
doubleTypes.add(132.2d,222.4d);
}
}
Here is the output of above example.
Sum of numbers is 33.0
Multiplication of numbers is 242.0
Sum of numbers is 54.60000038146973
Sum of numbers is 354.6
Web development and Automation testing
solutions delivered!!