Monday, April 3, 2023
Java Concurrency: The Lock interface
Friday, October 14, 2022
Implement Interface using Abstract Class in Java
1. Let’s create an Interface at first:
2. Now let’s implement the interface in an Abstract class named Student:
3. Now let’s create a class JAVA which extends the abstract class, Student:
Output:
Thursday, April 28, 2022
Bruce Eckel on Java interfaces and sealed classes
With the introduction of default and static methods in interfaces, Java made it possible to write method code in an interface that you might not want to be public. In the code below, Old, fd(), and fs() are default and static methods, respectively. These methods are called only by f() and g(), so you can make them private.
// interfaces/PrivateInterfaceMethods.java
// {NewFeature} Since JDK 9
interface Old {
default void fd() {
System.out.println("Old::fd()");
}
static void fs() {
System.out.println("Old::fs()");
}
default void f() {
fd();
}
static void g() {
fs();
}
}
class ImplOld implements Old {}
interface JDK9 {
private void fd() { // Automatically default
System.out.println("JDK9::fd()");
}
private static void fs() {
System.out.println("JDK9::fs()");
}
default void f() {
fd();
}
static void g() {
fs();
}
}
class ImplJDK9 implements JDK9 {}
public class PrivateInterfaceMethods {
public static void main(String[] args) {
new ImplOld().f();
Old.g();
new ImplJDK9().f();
JDK9.g();
}
}
/* Output:
Old::fd()
Old::fs()
JDK9::fd()
JDK9::fs()
*/
(Note: The {NewFeature} comment tag excludes this example from the Gradle build that uses JDK 8.)
JDK9 turns fd() and fs() into private methods using the feature finalized in JDK 9. Note that fd() no longer needs the default keyword, as making it private automatically makes it default.
Sealed classes and interfaces
An enumeration creates a class that has only a fixed number of instances. JDK 17 finalizes the introduction of sealed classes and interfaces, so the base class or interface can constrain what classes can be derived from it. This allows you to model a fixed set of kinds of values.
// interfaces/Sealed.java
// {NewFeature} Since JDK 17
sealed class Base permits D1, D2 {}
final class D1 extends Base {}
final class D2 extends Base {}
// Illegal:
// final class D3 extends Base {}
The compiler produces an error if you try to inherit a subclass such as D3 that is not listed in the permits clause. In the code above, there can be no subclasses other than D1 and D2. Thus, you can ensure that any code you write will only ever need to consider D1 and D2.
You can also seal interfaces and abstract classes.
// interfaces/SealedInterface.java
// {NewFeature} Since JDK 17
sealed interface Ifc permits Imp1, Imp2 {}
final class Imp1 implements Ifc {}
final class Imp2 implements Ifc {}
sealed abstract class AC permits X {}
final class X extends AC {}
If all subclasses are defined in the same file, you don’t need the permits clause. In the following, the compiler will prevent any attempt to inherit a Shape outside of SameFile.java:
// interfaces/SameFile.java
// {NewFeature} Since JDK 17
sealed class Shape {}
final class Circle extends Shape {}
final class Triangle extends Shape {}
The permits clause allows you to define the subclasses in separate files, as follows:
// interfaces/SealedPets.java
// {NewFeature} Since JDK 17
sealed class Pet permits Dog, Cat {}
// interfaces/SealedDog.java
// {NewFeature} Since JDK 17
final class Dog extends Pet {}
// interfaces/SealedCat.java
// {NewFeature} Since JDK 17
final class Cat extends Pet {}
Subclasses of a sealed class must be modified by one of the following:
◉ final: No further subclasses are allowed.
◉ sealed: A sealed set of subclasses is allowed.
◉ non-sealed: This is a new keyword that allows inheritance by unknown subclasses.
The sealed subclasses maintain strict control of the hierarchy.
// interfaces/SealedSubclasses.java
// {NewFeature} Since JDK 17
sealed class Bottom permits Level1 {}
sealed class Level1 extends Bottom permits Level2 {}
sealed class Level2 extends Level1 permits Level3 {}
final class Level3 extends Level2 {}
Note that a sealed class must have at least one subclass.
A sealed base class cannot prevent the use of a non-sealed subclass, so you can always open things back up.
// interfaces/NonSealed.java
// {NewFeature} Since JDK 17
sealed class Super permits Sub1, Sub2 {}
final class Sub1 extends Super {}
non-sealed class Sub2 extends Super {}
class Any1 extends Sub2 {}
class Any2 extends Sub2 {}
Sub2 allows any number of subclasses, so it seems like it releases control of the types you can create. However, you strictly limit the immediate subclasses of the sealed class Super. That is, Super still allows only the direct subclasses Sub1 and Sub2.
A JDK 16 record (described in a previous article in this series) can also be used as a sealed implementation of an interface. Because a record is implicitly final, it does not need to be preceded by the final keyword.
// interfaces/SealedRecords.java
// {NewFeature} Since JDK 17
sealed interface Employee
permits CLevel, Programmer {}
record CLevel(String type)
implements Employee {}
record Programmer(String experience)
implements Employee {}
The compiler prevents you from downcasting to illegal types from within a sealed hierarchy.
// interfaces/CheckedDowncast.java
// {NewFeature} Since JDK 1
sealed interface II permits JJ {}
final class JJ implements II {}
class Something {}
public class CheckedDowncast {
public void f() {
II i = new JJ();
JJ j = (JJ)i;
// Something s = (Something)i;
// error: incompatible types: II cannot
// be converted to Something
}
}
You can discover the permitted subclasses at runtime using the getPermittedSubclasses() call, as follows:
// interfaces/PermittedSubclasses.java
// {NewFeature} Since JDK 17
sealed class Color permits Red, Green, Blue {}
final class Red extends Color {}
final class Green extends Color {}
final class Blue extends Color {}
public class PermittedSubclasses {
public static void main(String[] args) {
for(var p: Color.class.getPermittedSubclasses())
System.out.println(p.getSimpleName());
}
}
/* Output:
Red
Green
Blue
*/
Source: oracle.com
Monday, September 20, 2021
Differences between Interface and Class in Java
This article highlights the differences between a class and an interface in Java.
Class:
A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order:
1. Modifiers: A class can be public or has default access.
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.
Constructors are used for initializing new objects. Fields are variables that provides the state of the class and its objects, and methods are used to implement the behavior of the class and its objects.
Example:
// Java program to demonstrate Class
// Class Declaration
public class Dog {
// Instance Variables
String name;
String breed;
int age;
String color;
// Constructor Declaration of Class
public Dog(String name, String breed,
int age, String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}
// method 1
public String getName()
{
return name;
}
// method 2
public String getBreed()
{
return breed;
}
// method 3
public int getAge()
{
return age;
}
// method 4
public String getColor()
{
return color;
}
@Override
public String toString()
{
return ("Hi my name is "
+ this.getName()
+ ".\nMy breed, age and color are "
+ this.getBreed() + ", "
+ this.getAge() + ", "
+ this.getColor());
}
public static void main(String[] args)
{
Dog tuffy = new Dog("tuffy", "papillon",
5, "white");
System.out.println(tuffy.toString());
}
}
Interface:
Differences between a Class and an Interface:
Class | Interface |
The keyword used to create a class is “class” | The keyword used to create an interface is “interface” |
A class can be instantiated i.e, objects of a class can be created. | An Interface cannot be instantiated i.e, objects cannot be created. |
Classes does not support multiple inheritance. | Interface supports multiple inheritance. |
It can be inherit another class. | It cannot inherit a class. |
It can be inherited by another class using the keyword ‘extends’. | It can be inherited by a class by using the keyword ‘implements’ and it can be inherited by an interface using the keyword ‘extends’. |
It can contain constructors. | It cannot contain constructors. |
It cannot contain abstract methods. | It contains abstract methods only. |
Variables and methods in a class can be declared using any access specifier(public, private, default, protected) | All variables and methods in a interface are declared as public. |
Variables in a class can be static, final or neither. | All variables are static and final. |
Friday, August 20, 2021
Java 8 - Functional Interfaces
Functional interfaces have a single functionality to exhibit. For example, a Comparable interface with a single method ‘compareTo’ is used for comparison purpose. Java 8 has defined a lot of functional interfaces to be used extensively in lambda expressions. Following is the list of functional interfaces defined in java.util.Function package.
Functional Interface Example
Predicate <T> interface is a functional interface with a method test(Object) to return a Boolean value. This interface signifies that an object is tested to be true or false.
Create the following Java program using any editor of your choice in, say, C:\> JAVA.
Java8Tester.java
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class Java8Tester {
public static void main(String args[]) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
// Predicate<Integer> predicate = n -> true
// n is passed as parameter to test method of Predicate interface
// test method will always return true no matter what value n has.
System.out.println("Print all numbers:");
//pass n as parameter
eval(list, n->true);
// Predicate<Integer> predicate1 = n -> n%2 == 0
// n is passed as parameter to test method of Predicate interface
// test method will return true if n%2 comes to be zero
System.out.println("Print even numbers:");
eval(list, n-> n%2 == 0 );
// Predicate<Integer> predicate2 = n -> n > 3
// n is passed as parameter to test method of Predicate interface
// test method will return true if n is greater than 3.
System.out.println("Print numbers greater than 3:");
eval(list, n-> n > 3 );
}
public static void eval(List<Integer> list, Predicate<Integer> predicate) {
for(Integer n: list) {
if(predicate.test(n)) {
System.out.println(n + " ");
}
}
}
}
Here we've passed Predicate interface, which takes a single input and returns Boolean.
Verify the Result
Compile the class using javac compiler as follows −
C:\JAVA>javac Java8Tester.java
Now run the Java8Tester as follows −
C:\JAVA>java Java8Tester
It should produce the following output −
Print all numbers:
1
2
3
4
5
6
7
8
9
Print even numbers:
2
4
6
8
Print numbers greater than 3:
4
5
6
7
8
9
Source: tutorialspoint.com
Friday, July 30, 2021
Interfaces and Polymorphism in Java
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JA is that Java tries to connect every concept in the language to the real world with the help of the concepts of classes, inheritance, polymorphism, interfaces, etc. In this article, we will discuss polymorphism and interface concepts.
Polymorphism is that it has many forms that mean one specific defined form is used in many different ways. The simplest real-life example is let’s suppose we have to store the name of the person and the phone number of the person, but there are many situations when a person has two different phone numbers. We have to save the same phone number under the same name.
Let us interpret it with help . So, in java, the problem can be solved using an object-oriented concept, void insertPhone(String name, int phone). So, this method is used to save the phone number of the particular person. Similarly, we can use the same form but a different signature means different parameters to store the alternative phone number of the person’s void insertPhone(String name, int phone1, int phone2). One method has two different forms and performs different operations. This is an example of polymorphism, which is method overloading.
Types of polymorphism in Java:
1. Run time polymorphism
2. Compile-time polymorphism
Type 1: Run time polymorphism
This type of polymorphism is resolved by the java virtual machine, not by the java compiler. That’s why this type of polymorphism is called run-time polymorphism. Run time polymorphism occurs during method overriding in java.
Example
// Java Program to Illustrate Run-time polymorphism
// Importing I/O classes
import java.io.*;
// Class 1 (Parent class)
class GFG1 {
//name method
void name() {
System.out.println("This is the GFG1 class");
}
}
// Class 2 (Chile class)
// Main class extending parent class
public class GFG extends GFG1 {
// Method 1
void name() {
// Print statement
System.out.println("This is the GFG class");
}
// Method 2
// Main drive method
public static void main(String[] args) {
// Now creating 2 objects with different references and
// calling the Method 1 over the objects
// Case 1: GFG1 reference and GFG1 is the object
GFG1 ob = new GFG1();
ob.name();
// Case 2: GFG1 reference and GFG is the object
GFG1 ob1 = new GFG();
ob1.name();
}
}
Monday, April 19, 2021
Difference Between Package and Interface in Java
The key difference between Package and Interface in Java is that Package helps to categorize the classes methodically to access and maintain them easily while Interface helps to implement multiple inheritances and to achieve abstraction.
Java is one of the most popular programming languages. The main advantage of Java is that it supports Object Oriented Programming. This methodology allows modeling the real world objects in software. A class is a blueprint to create an object. Each object contains data or fields to describe the attributes or the properties and methods to describe behaviors. This article discusses two concepts related to OOP in Java in Java that are Package and Interface.
What is Package in Java?
Java provides a large number of classes. Keeping all the classes in a single folder can be difficult because it is hard to access. This can affect the program manageability. Java uses packages to arrange classes. It is similar to a folder. Java API groups classes into different packages according to the functionality. Therefore, each package contains a related set of classes.
Example of Packages in Java
Few example packages are as follows. The java.io package contains the input, output supporting classes. It includes File, PrintStream, BufferInputStream etc. The java.net package contains the networking related classes. Some examples are URL, Socket, ServerSocket. The java.awt package contains all the classes required to build Graphical User Interfaces. Those are few Java API packages.
Read More: 1Z0-900: Java EE 7 Application Developer
When the programmer wants to use a certain class in the program, he should import that package. If the programmer wants to use the BufferInputStream class in the java.io package, he should write the import statement as follows.
import java.util.BufferInoutStream;
Below statement will import all the classes in the util package.
import java.util.*;
It is also possible to create user defined packages.
package employee;
public class Employee {
}
According to the above example, the employee is the package name. The Employee class is a part of the employee package. This file saves as Employee.java to the employee package.
Furthermore, it is possible to import a public class from one package to another. Refer the following example.
What is Interface in Java?
Example of Interface in Java
What is the Difference Between Package and Interface in Java?
Friday, February 19, 2021
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
Abstract class | Interface |
Abstract class can have abstract and non-abstract methods. | Interface can have only abstract methods. Since Java 8, it can have default and static methods also. |
Abstract class doesn't support multiple inheritance. | Interface supports multiple inheritance. |
Abstract class can have final, non-final, static and non-static variables. | Interface has only static and final variables. |
Abstract class can provide the implementation of interface. | Interface can't provide the implementation of abstract class. |
The abstract keyword is used to declare abstract class. | Interface can't provide the implementation of abstract class. |
An abstract class can extend another Java class and implement multiple Java interfaces. | An interface can extend another Java interface only. |
An abstract class can be extended using keyword "extends". | An interface can be implemented using keyword "implements". |
A Java abstract class can have class members like private, protected, etc. | Members of a Java interface are public by default. |
Example: public abstract class Shape{ public abstract void draw(); } |
Example: public interface Drawable{ void draw(); } |
Example of abstract class and interface in Java
Wednesday, October 28, 2020
Comparator Interface in Java with Examples
Comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of two different classes. Following function compare obj1 with obj2
Syntax:
public int compare(Object obj1, Object obj2):
Suppose we have an array/arraylist of our own class type, containing fields like rollno, name, address, DOB etc and we need to sort the array based on Roll no or name?
Method 1: One obvious approach is to write our own sort() function using one of the standard algorithms. This solution requires rewriting the whole sorting code for different criterion like Roll No. and Name.
Method 2: Using comparator interface- Comparator interface is used to order the objects of user-defined class. This interface is present in java.util package and contains 2 methods compare(Object obj1, Object obj2) and equals(Object element). Using comparator, we can sort the elements based on data members. For instance it may be on rollno, name, age or anything else.
Method of Collections class for sorting List elements is used to sort the elements of List by the given comparator.
// To sort a given list. ComparatorClass must implement
// Comparator interface.
public void sort(List list, ComparatorClass c)
How does Collections.Sort() work?
Sort collection by more than one field:
Monday, October 5, 2020
Difference between Abstract Class and Interface in Java
Prerequisite
Interface
An interface is an abstract "class" that is used to group related methods with "empty" bodies: To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of extends ).
Abstract Class
Abstract class is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
Abstraction: Hiding the internal implementation of the feature and only showing the functionality to the users. i.e. what it works (showing), how it works (hiding). Both abstract class and interface are used for abstraction.
Abstract class vs Interface
1. Type of methods: Interface can have only abstract methods. Abstract class can have abstract and non-abstract methods. From Java 8, it can have default and static methods also.
2. Final Variables: Variables declared in a Java interface are by default final. An abstract class may contain non-final variables.
3. Type of variables: Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables.
4. Implementation: Abstract class can provide the implementation of interface. Interface can’t provide the implementation of abstract class.
5. Inheritance vs Abstraction: A Java interface can be implemented using keyword “implements” and abstract class can be extended using keyword “extends”.
6. Multiple implementation: An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
7. Accessibility of Data Members: Members of a Java interface are public by default. A Java abstract class can have class members like private, protected, etc.
When to use what?
- In java application, there are some related classes that need to share some lines of code then you can put these lines of code within abstract class and this abstract class should be extended by all these related classes.
- You can define non-static or non-final field(s) in abstract class, so that via a method you can access and modify the state of Object to which they belong.
- You can expect that the classes that extend an abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
- It is total abstraction, All methods declared within an interface must be implemented by the class(es) that implements this interface.
- A class can implement more than one interface. It is called multiple inheritance.
- You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.