As it implementing the Human interface it must provide the body of all the methods those defined in the Human interface.
CE204 Object-Oriented Programming
Implementing an Interface in Java Example-2
interfacePolygon{
voidgetArea(int length, int breadth);
}
// implement the Polygon interfaceclassRectangleimplementsPolygon{
// implementation of abstract methodpublicvoidgetArea(int length, int breadth){
System.out.println("The area of the rectangle is " + (length * breadth));
}
}
Here, the Polygon interface extends the Line interface. Now, if any class implements Polygon, it should provide implementations for all the abstract methods of both Line and Polygon
interfaceLine{
// members of Line interface
}
// extending interfaceinterfacePolygonextendsLine{
// members of Polygon interface// members of Line interface
}
CE204 Object-Oriented Programming
Extending Multiple Interfaces in Java Example
interfaceA{
...
}
interfaceB{
...
}
interfaceCextendsA, B{
...
}
CE204 Object-Oriented Programming
Advantages of Interface in Java
CE204 Object-Oriented Programming
Advantages of Interface in Java
Similar to abstract classes, interfaces help us to achieve abstraction in Java
Here, we know getArea() calculates the area of polygons but the way area is calculated is different for different polygons. Hence, the implementation of getArea() is independent of one another.
CE204 Object-Oriented Programming
Advantages of Interface in Java
Interfaces provide specifications that a class (which implements it) must follow.
In our previous example, we have used getArea() as a specification inside the interface Polygon. This is like setting a rule that we should be able to get the area of every polygon.
Now any class that implements the Polygon interface must provide an implementation for the getArea() method.
CE204 Object-Oriented Programming
Advantages of Interface in Java
Interfaces are also used to achieve multiple inheritance in Java
In the example, the class Rectangle is implementing two different interfaces. This is how we achieve multiple inheritance in Java.
All the methods inside an interface are implicitly public and all fields are implicitly public static final. For example,
interfaceLanguage{
// by default public static final
String type = "programming language";
// by default publicvoidgetName();
}
CE204 Object-Oriented Programming
default methods in Java Interfaces
CE204 Object-Oriented Programming
default methods in Java Interfaces
With the release of Java 8, we can now add methods with implementation inside an interface.
These methods are called default methods.
To declare default methods inside interfaces, we use the default keyword. For example,
publicdefaultvoidgetSides(){
// body of getSides()
}
CE204 Object-Oriented Programming
why default methods in Java Interfaces
Let's take a scenario to understand why default methods are introduced in Java.
Suppose, we need to add a new method in an interface.
We can add the method in our interface easily without implementation. However, that's not the end of the story. All our classes that implement that interface must provide an implementation for the method.
If a large number of classes were implementing this interface, we need to track all these classes and make changes to them. This is not only tedious but error-prone as well.
To resolve this, Java introduced default methods. Default methods are inherited like ordinary methods.
CE204 Object-Oriented Programming
Default Method in Java Interface Example
interfacePolygon{
voidgetArea();
// default method defaultvoidgetSides(){
System.out.println("I can get sides of a polygon.");
}
}
CE204 Object-Oriented Programming
Default Method in Java Interface Example
// implements the interfaceclassRectangleimplementsPolygon{
publicvoidgetArea(){
int length = 6;
int breadth = 5;
int area = length * breadth;
System.out.println("The area of the rectangle is " + area);
}
// overrides the getSides()publicvoidgetSides(){
System.out.println("I have 4 sides.");
}
}
CE204 Object-Oriented Programming
Default Method in Java Interface Example
// implements the interfaceclassSquareimplementsPolygon{
publicvoidgetArea(){
int length = 5;
int area = length * length;
System.out.println("The area of the square is " + area);
}
}
CE204 Object-Oriented Programming
Default Method in Java Interface Example
classMain{
publicstaticvoidmain(String[] args){
// create an object of Rectangle
Rectangle r1 = new Rectangle();
r1.getArea();
r1.getSides();
// create an object of Square
Square s1 = new Square();
s1.getArea();
s1.getSides();
}
}
CE204 Object-Oriented Programming
Default Method in Java Interface Example
In the example, we have created an interface named Polygon. It has a default method getSides() and an abstract method getArea().
Here, we have created two classes Rectangle and Square that implement Polygon.
The Rectangle class provides the implementation of the getArea() method and overrides the getSides() method. However, the Square class only provides the implementation of the getArea() method.
Now, while calling the getSides() method using the Rectangle object, the overridden method is called. However, in the case of the Square object, the default method is called.
CE204 Object-Oriented Programming
private and static Methods in Interface
CE204 Object-Oriented Programming
private and static Methods in Interface
The Java 8 also added another feature to include static methods inside an interface.
Similar to a class, we can access static methods of an interface using its references. For example,
Note: With the release of Java 9, private methods are also supported in interfaces.
We cannot create objects of an interface.
Hence, private methods are used as helper methods that provide support to other methods in interfaces.
CE204 Object-Oriented Programming
Java Interface Practical Example
// To use the sqrt functionimport java.lang.Math;
interfacePolygon{
voidgetArea();
// calculate the perimeter of a PolygondefaultvoidgetPerimeter(int... sides){
int perimeter = 0;
for (int side: sides) {
perimeter += side;
}
System.out.println("Perimeter: " + perimeter);
}
}
CE204 Object-Oriented Programming
Java Interface Practical Example
classTriangleimplementsPolygon{
privateint a, b, c;
privatedouble s, area;
// initializing sides of a triangle
Triangle(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
s = 0;
}
// calculate the area of a trianglepublicvoidgetArea(){
s = (double) (a + b + c)/2;
area = Math.sqrt(s*(s-a)*(s-b)*(s-c));
System.out.println("Area: " + area);
}
}
CE204 Object-Oriented Programming
Java Interface Practical Example
classMain{
publicstaticvoidmain(String[] args){
Triangle t1 = new Triangle(2, 3, 4);
// calls the method of the Triangle class
t1.getArea();
// calls the method of Polygon
t1.getPerimeter(2, 3, 4);
}
}
CE204 Object-Oriented Programming
Java Interface Practical Example
In the example, we have created an interface named Polygon.
It includes a default method getPerimeter() and an abstract method getArea().
We can calculate the perimeter of all polygons in the same manner so we implemented the body of getPerimeter() in Polygon.
Now, all polygons that implement Polygon can use getPerimeter() to calculate perimeter.
However, the rule for calculating the area is different for different polygons.
Hence, getArea() is included without implementation.
Any class that implements Polygon must provide an implementation of getArea().
CE204 Object-Oriented Programming
Java Reflection
CE204 Object-Oriented Programming
Java Reflection
In Java, reflection allows us to inspect and manipulate classes, interfaces, constructors, methods, and fields at run time.
There is a class in Java named Class that keeps all the information about objects and classes at runtime. The object of Class can be used to perform reflection.
CE204 Object-Oriented Programming
Reflection of Java Classes
In order to reflect a Java class, we first need to create an object of Class.
And, using the object we can call various methods to get information about methods, fields, and constructors present in a class.
There exists three ways to create objects of Class:
CE204 Object-Oriented Programming
Reflection of Java Classes
Using forName() method
classDog{...}
// create object of Class// to reflect the Dog class
Class a = Class.forName("Dog");
Here, the forName() method takes the name of the class to be reflected as its argument.
CE204 Object-Oriented Programming
Reflection of Java Classes
Using getClass() method
// create an object of Dog class
Dog d1 = new Dog();
// create an object of Class// to reflect Dog
Class b = d1.getClass();
Here, we are using the object of the Dog class to create an object of Class.
CE204 Object-Oriented Programming
Reflection of Java Classes
Using .class extension
// create an object of Class// to reflect the Dog class
Class c = Dog.class;
Now that we know how we can create objects of the Class.
We can use this object to get information about the corresponding class at runtime.
CE204 Object-Oriented Programming
Java Class Reflection Example
import java.lang.Class;
import java.lang.reflect.*;
classAnimal{
}
// put this class in different Dog.java filepublicclassDogextendsAnimal{
publicvoiddisplay(){
System.out.println("I am a dog.");
}
}
CE204 Object-Oriented Programming
Java Class Reflection Example
// put this in Main.java fileclassMain{
publicstaticvoidmain(String[] args){
try {
// create an object of Dog
Dog d1 = new Dog();
// create an object of Class// using getClass()
Class obj = d1.getClass();
// get name of the class
String name = obj.getName();
System.out.println("Name: " + name);
// get the access modifier of the classint modifier = obj.getModifiers();
// convert the access modifier to string
String mod = Modifier.toString(modifier);
System.out.println("Modifier: " + mod);
// get the superclass of Dog
Class superClass = obj.getSuperclass();
System.out.println("Superclass: " + superClass.getName());
}catch (Exception e) { e.printStackTrace();}
}
}
CE204 Object-Oriented Programming
Java Class Reflection Example
In the example, we have created a superclass: Animal and a subclass: Dog. Here, we are trying to inspect the class Dog.
Notice the statement,
Class obj = d1.getClass();
Here, we are creating an object obj of Class using the getClass() method. Using the object, we are calling different methods of Class.
obj.getName() - returns the name of the class
obj.getModifiers() - returns the access modifier of the class
obj.getSuperclass() - returns the super class of the class
Note: We are using the Modifier class to convert the integer access modifier to a string.
CE204 Object-Oriented Programming
Reflecting Fields, Methods, and Constructors
The package java.lang.reflect provides classes that can be used for manipulating class members. For example,
Method class - provides information about methods in a class
Field class - provides information about fields in a class
Constructor class - provides information about constructors in a class
CE204 Object-Oriented Programming
Reflection of Java Methods
The Method class provides various methods that can be used to get information about the methods present in a class.
CE204 Object-Oriented Programming
Reflection of Java Methods Example
import java.lang.Class;
import java.lang.reflect.*;
classDog{
// methods of the classpublicvoiddisplay(){
System.out.println("I am a dog.");
}
privatevoidmakeSound(){
System.out.println("Bark Bark");
}
}
CE204 Object-Oriented Programming
Reflection of Java Methods Example
classMain{
publicstaticvoidmain(String[] args){
try {
// create an object of Dog
Dog d1 = new Dog();
// create an object of Class// using getClass()
Class obj = d1.getClass();
// using object of Class to// get all the declared methods of Dog
Method[] methods = obj.getDeclaredMethods();
...
CE204 Object-Oriented Programming
Reflection of Java Methods Example
...
// create an object of the Method classfor (Method m : methods) {
// get names of methods
System.out.println("Method Name: " + m.getName());
// get the access modifier of methodsint modifier = m.getModifiers();
System.out.println("Modifier: " + Modifier.toString(modifier));
// get the return types of method
System.out.println("Return Types: " + m.getReturnType());
System.out.println(" ");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
CE204 Object-Oriented Programming
Reflection of Java Methods Example
In the example, we are trying to get information about the methods present in the Dog class.
As mentioned earlier, we have first created an object obj of Class using the getClass() method.
Notice the expression,
Method[] methods = obj.getDeclaredMethod();
Here, the getDeclaredMethod() returns all the methods present inside the class.
CE204 Object-Oriented Programming
Reflection of Java Methods Example
Also, we have created an object m of the Method class. Here,
m.getName() - returns the name of a method
m.getModifiers() - returns the access modifier of methods in integer form
m.getReturnType() - returns the return type of methods
The Method class also provides various other methods that can be used to inspect methods at run time.
CE204 Object-Oriented Programming
Reflection of Java Fields
Like methods, we can also inspect and modify different fields of a class using the methods of the Field class.
CE204 Object-Oriented Programming
Reflection of Java Public Fields Example
import java.lang.Class;
import java.lang.reflect.*;
classDog{
public String type;
}
CE204 Object-Oriented Programming
Reflection of Java Public Fields Example
classMain{
publicstaticvoidmain(String[] args){
try {
// create an object of Dog
Dog d1 = new Dog();
// create an object of Class// using getClass()
Class obj = d1.getClass();
// access and set the type field
Field field1 = obj.getField("type");
field1.set(d1, "labrador");
...
CE204 Object-Oriented Programming
Reflection of Java Public Fields Example
...
// get the value of the field type
String typeValue = (String) field1.get(d1);
System.out.println("Value: " + typeValue);
// get the access modifier of the field typeint mod = field1.getModifiers();
// convert the modifier to String form
String modifier1 = Modifier.toString(mod);
System.out.println("Modifier: " + modifier1);
System.out.println(" ");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
CE204 Object-Oriented Programming
Reflection of Java Public Fields Example
In the example, we have created a class named Dog.
It includes a public field named type. Notice the statement,
Field field1 = obj.getField("type");
Here, we are accessing the public field of the Dog class and assigning it to the object field1 of the Field class.
We then used various methods of the Field class:
field1.set() - sets the value of the field
field1.get() - returns the value of field
field1.getModifiers() - returns the value of the field in integer form
CE204 Object-Oriented Programming
Reflection of Java Private Fields Example
Similarly, we can also access and modify private fields as well. However, the reflection of private field is little bit different than the public field
classMain{
publicstaticvoidmain(String[] args){
try {
// create an object of Dog
Dog d1 = new Dog();
// create an object of Class// using getClass()
Class obj = d1.getClass();
// access the private field color
Field field1 = obj.getDeclaredField("color");
// allow modification of the private field
field1.setAccessible(true);
...
CE204 Object-Oriented Programming
Reflection of Java Private Fields Example
...
// set the value of color
field1.set(d1, "brown");
// get the value of field color
String colorValue = (String) field1.get(d1);
System.out.println("Value: " + colorValue);
// get the access modifier of colorint mod2 = field1.getModifiers();
// convert the access modifier to string
String modifier2 = Modifier.toString(mod2);
System.out.println("Modifier: " + modifier2);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
CE204 Object-Oriented Programming
Reflection of Java Private Fields Example
In the example, we have created a class named Dog.
The class contains a private field named color. Notice the statement.
Field field1 = obj.getDeclaredField("color");
field1.setAccessible(true);
Here, we are accessing color and assigning it to the object field1 of the Field class.
We then used field1 to modify the accessibility of color and allows us to make changes to it.
We then used field1 to perform various operations on the private field color.
CE204 Object-Oriented Programming
Reflection of Java Constructor
We can also inspect different constructors of a class using various methods provided by the Constructor class
CE204 Object-Oriented Programming
Reflection of Java Constructor Example
import java.lang.Class;
import java.lang.reflect.*;
classDog{
// public constructor without parameterpublicDog(){
}
// private constructor with a single parameterprivateDog(int age){
}
}
CE204 Object-Oriented Programming
Reflection of Java Constructor Example
classMain{
publicstaticvoidmain(String[] args){
try {
// create an object of Dog
Dog d1 = new Dog();
// create an object of Class// using getClass()
Class obj = d1.getClass();
// get all constructors of Dog
Constructor[] constructors = obj.getDeclaredConstructors();
...
CE204 Object-Oriented Programming
Reflection of Java Constructor Example
...
for (Constructor c : constructors) {
// get the name of constructors
System.out.println("Constructor Name: " + c.getName());
// get the access modifier of constructors// convert it into string formint modifier = c.getModifiers();
String mod = Modifier.toString(modifier);
System.out.println("Modifier: " + mod);
// get the number of parameters in constructors
System.out.println("Parameters: " + c.getParameterCount());
System.out.println("");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
CE204 Object-Oriented Programming
Reflection of Java Constructor Example
In the example, we have created a class named Dog. The class includes two constructors.
We are using reflection to find the information about the constructors of the class. Notice the statement,
Here, the we are accessing all the constructors present in Dog and assigning them to an array constructors of the Constructor type.
CE204 Object-Oriented Programming
Reflection of Java Constructor Example
We then used object c to get different informations about the constructor.
c.getName() - returns the name of the constructor
c.getModifiers() - returns the access modifiers of the constructor in integer form
c.getParameterCount() - returns the number of parameters present in each constructor
CE204 Object-Oriented Programming
Java Wrapper Classes
CE204 Object-Oriented Programming
Java Wrapper Classes
Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects
Primitive Data Type ⟹ Wrapper Class
byte ⟹ Byte
short ⟹ Short
int ⟹ Integer
long ⟹ Long
float ⟹ Float
double ⟹ Double
boolean ⟹ Boolean
char ⟹ Character
CE204 Object-Oriented Programming
Java Wrapper Classes
Sometimes you must use wrapper classes, for example when working with Collection objects, such as ArrayList, where primitive types cannot be used (the list can only store objects)
ArrayList<int> myNumbers = new ArrayList<int>(); // Invalid
ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // Valid
CE204 Object-Oriented Programming
Creating Wrapper Objects
To create a wrapper object, use the wrapper class instead of the primitive type. To get the value, you can just print the object
Since you're now working with objects, you can use certain methods to get information about the specific object.
For example, the following methods are used to get the value associated with the corresponding wrapper object: intValue(), byteValue(), shortValue(), longValue(), floatValue(), doubleValue(), charValue(), booleanValue().
A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.
CE204 Object-Oriented Programming
Java Lambda Expressions Syntax
The simplest lambda expression contains a single parameter and an expression:
parameter -> expression
To use more than one parameter, wrap them in parentheses:
(parameter1, parameter2) -> expression
CE204 Object-Oriented Programming
Java Lambda Expressions Syntax
Expressions are limited. They have to immediately return a value, and they cannot contain variables, assignments or statements such as if or for. In order to do more complex operations, a code block can be used with curly braces. If the lambda expression needs to return a value, then the code block should have a return statement.
(parameter1, parameter2) -> { code block }
CE204 Object-Oriented Programming
Lambda expressions are usually passed as parameters to a function
CE204 Object-Oriented Programming
Using Lambda Expressions
Use a lamba expression in the ArrayList's forEach() method to print every item in the list