Interfaces in JAVA - Interview JAVA questions - Interfaces part1 Java - UCS - Unleash-Coding-Skills

Thursday, 24 May 2018

Interfaces in JAVA - Interview JAVA questions - Interfaces part1 Java - UCS

Interface in Java:

An interface in java is a blueprint of a class. It has static constants and abstract methods.

The interface is consists of method declarations and constants.All fields in interface are final,public and static.

With the help of interfaces JAVA support Multiple Inheritance in java.The interface are reusable as like classes in java.

All the methods in the interface must be implemented in the class that implemented it.Otherwise the following error occur for example.

interface A
{
    void x();
    void u();
    int x=1;
}

class R implements A
{
public void x()
{
System.out.println("h");
}
}

public class InterfacePractice1 {
    public static void main(String args[])
    {
     B a  = new R();   
     a.y();
    }
}

Output:


InterfacePractice1.java:11: error: R is not abstract and does not override abstr
act method u() in A
class R implements A

Correct Solution for implementing interface:

So to implement it correctly we need to implement all methods in the interface in the implemented class.The following is complete implementation for interface in java.

import java.util.*;
import java.io.*;
import java.lang.*;
interface A
{
    void x();
    void u();
    int x=1;
}

class R implements A
{
public void x()
{
System.out.println("h");
}
public void u()
{
System.out.println("p");
}
}

public class InterfacePractice1 {
    public static void main(String args[])
    {
     A a  = new R();   
     a.x();
     a.u();
    }
}

Output:

h
p

Incase if you try to change the values of constants in implemented class of interface it will show error.
Happy Coding.......

Java Interfaces Part2:

Can two interfaces with same prototype method can be implemented in a single class at a time.Its a interview question.Find the solution.Subscribe for more interesting things.

https://www.unleashcodingskills.com/2018/05/interfaces-java-interfaces-part2-can.html


Tags:
Interface in java,Java interface, Interface Errors in java,Java Interface Example,Java interface examples with error messages,Errors for implementing java interface,Interfaces in Object oriented language in java.

No comments:

Post a comment