PhysicsTeacher.in

High School Physics

Java Program – how to extend a base class and implement multiple interfaces from a child class?

Here is a Java program that helps you to understand how to extend a base class and implement multiple interfaces from a child class. This program also shows how a Java interface can extend another Java interface.

Note:
1)You will find some informative texts in the program that are commented with either // or /**/.
2) As well as you will find some commented java statements, these are also for your training and understanding, and you will get the corresponding Java tips (stating why that statement won’t compile or run there) for that specific line just before or after the commented statements.

Java Program – a child class extends a base class and implements multiple interfaces | Interface hierarchy

interface IntTest
{
void callBack();
int ivar=10;//its final implicitly, value must be assined
}

interface I2 extends IntTest
{
void callmeToo();
/*System.out.println(ivar); we cant execute this type of command here as its outside any method. and no method with body is allowed in an interface*/
//void test(){} /*not compile as “interface methods cannot have body”*/
}

class Emp
{
int empid=1924;
}

interface I3
{

//assigning a value is a must, its final
int roll=307;
}

class InterfaceTest2 extends Emp implements I2,I3
{
public void callBack()//must be declared public
{
System.out.println(“In callBack method”);
/*ivar=2; wont compile,error: cannot assign a value to final variable ivar*/

//ivar accessible here, but u cant modify its val..its final
System.out.println(“ivar=”+ivar);
}

public void callmeToo()
{
}

public static void main(String args[])
{
InterfaceTest2 i1=new InterfaceTest2();
i1.callBack();
System.out.println(i1.empid);

/*roll is a final attr that came from interface I3.
its accessed thru an instance of the implementing class, in the next line*/
System.out.println(i1.roll);
}
}

See also  Java Program - how to use constructors in a Java class


Scroll to top
error: physicsTeacher.in