Program to implement the following Multiple Inheritance using interface
In multiple inheritance there are several super classes for a subclass. Java does not support Multiple inheritance. To achieve multiple inheritance in Java you have to use interface. The syntax for it is given below:
interface <interface-name> {
// variable declarations
// Method declarations (no implementation)
}
The implements keyword is used to for implementing interface and extends keyword is used to extend the class. The syntax for extending class and implementing interface is:
class <subclass-name> extends <superclass-name> implements <interface-name> {
// Body of subclass
}
In this program, we have created an interface Exam which has one method percent_cal( ) without implementation (body). Then we declare the class Student having data members name, roll_no, marks1, marks2 and one method display( ). Finally we extend the Student class and implement the Exam interface in Result class. You must override all the methods which a interface contains.
PROGRAM
import java.lang.*;
import java.io.*;
interface Exam {
void percent_cal();
}
class Student {
String name;
int roll_no,mark1,mark2;
Student(String n, int r, int m1, int m2) {
name=n;
roll_no=r;
mark1=m1;
mark2=m2;
}
void display() {
System.out.println ("Name of Student: "+name);
System.out.println ("Roll No. of Student: "+roll_no);
System.out.println ("Marks of Subject 1: "+mark1);
System.out.println ("Marks of Subject 2: "+mark2);
}
}
class Result extends Student implements Exam {
Result(String n, int r, int m1, int m2) {
super(n,r,m1,m2);
}
public void percent_cal() {
int total=(mark1+mark2);
float percent=total*100/200;
System.out.println ("Percentage: "+percent+"%");
}
void display() {
super.display();
}
}
public class MultipleInh {
public static void main(String[] args) {
Result R = new Result("Ragini",12,93,84);
R.display();
R.percent_cal();
}
}
OUTPUT
C:\>javac MultipleInh.java C:\>java MultipleInh Name of Student: Ragini Roll No. of Student: 12 Marks of Subject 1: 93 Marks of Subject 2: 84 Percentage: 88.0%
Comments
Post a Comment