Saturday 23 March 2013

Member Access Rules


1. By means of sub class object it is possible to access all the instance variables and instance methods of the super class.
2. By means of sub class object it cannot be possible to access the instance variable of super class, if it is declared as private.  Since, the data is protected in that class.


import javax.swing.JOptionPane;
class student
{
            private int rno;
            void readdata1()
            {
            rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number"));
            }
}
class exam extends student
{
            void printdata1()
            {
            readdata1();                                                           
            System.out.println("Roll Number="+rno);       // produces compilation error
            }
}
class mi2
{
            public static void main(String[] args)
            {
                        exam obj=new exam();
                        obj.printdata1();
            }
}



3. Referring to super class object with a subclass reference produces syntax error.  In such case we need type casting.
Example:

import javax.swing.JOptionPane;
class student
{
            int rno;
            void readdata1()
            {
            rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number"));
            }
}
class exam extends student
{
            void printdata1()
            {
            readdata1();
            System.out.println("Roll Number="+rno);
            }
}
class mi2
{
            public static void main(String[] args)
            {
                        student s1=new exam();
                        exam e1=(exam)s1;
                        e1.printdata1();
            }
}

No comments:

Post a Comment