Inheritance
When encapsulation is the first mechanism in Object Oriented Programming, the second fundamental Object Oriented mechanism is inheritance. This allows descendants of a class to inherit all of its member elements and methods from its ancestors as well as creates its own. These descendants are known as subclasses. A classes immediate parent is called its super class. In Java, a special key word extends is used to implement this mechanism. Following is the example to illustrate this.
import java.util.*;
class Student {
String Name;
int rno;
Scanner s=new Scanner(System.in);
void getdata() {
System.out.println("Enter The Name Of Student ->");
Name=s.nextLine();
System.out.println("Enter The Roll No Of Student ->");
rno=s.nextInt();
}
}
class Marks extends Student {
int cs;
int math;
int ele;
int tot;
int avg;
void getmarks() {
System.out.println("Enter The Marks For CS ,MATH And Ele Subjects ->");
cs=s.nextInt();
math=s.nextInt();
ele=s.nextInt();
}
void caltot() {
tot=cs+ele+math;
avg=tot/3;
}
void puttot() {
System.out.println("The Total Of Marks Of Student Is ="+tot);
System.out.println("The Average Of Marks Of Student Is ="+avg);
}
}
class SimpleInheritance {
public static void main(String[] args) {
Marks m=new Marks();
m.getdata();
m.getmarks();
m.caltot();
m.puttot();
}
}
Output
Enter The Name Of Student ->
sneha
Enter The Roll No Of Student ->
45
Enter The Marks For CS ,MATH And Ele Subjects ->
85
71
62
The Total Of Marks Of Student Is =218
The Average Of Marks Of Student Is =72
0 Comments