Member Access and Inheritance

A subclass includes all of the members of its super class but it cannot access those members of the super class that have been declared as private. Attempt to access a private variable would cause compilation error as it causes access violation. The variables declared as private, is only accessible by other members of its own class. Subclass have no access to it.

E.g.:

import java.io.*;
class Stud
{
String name;
int age;
double rollno;
Stud()
{
name="null";
age=-1;
rollno=-1;
}
Stud(String na, int a,double r)

name=na;
age=a
rollno=r;
}
void Disp()
{
System.out.println("Name:"+name);
System.out.println("Age:"+age);
System.out.println("Rollno:"+rollno);
}
}
class Studmark extends Stud
{
double mark;
Studmark(String name1,int age1,int rollno1,double mark1)
{
name=name1;
age=age1;
rollno=rollno1;
mark=mark1;
}
}
class Student
{
public static void main(String[] args)
{
Studmark s1=new Studmark("A",10,101,562);
Studmark s2=new Studmark("B",12,103,580);
System.out.println("First object");
s1.Disp();
System.out.println("Mark of s1"+s1.mark);
System.out.println("second object");
s2.Disp();
System.out.println("Mark of s2"+s2.mark);
}
}

Output:

First object
Name:A
Age:10
Rollno:101.0
Mark of s1:562.0
Second object
Name:B
Age:12
Rollno:103.0
Mark of s2:580.0

Note:

A major advantage of inheritance is that once you have created a super class that defines the attributes common to a set of objects, it can be used to create any number of more specific subclasses.

No comments:

Post a Comment