Hi... When I declare a method as private in a supper class, It's clear that sub classes cannot access that private method . If I create a instance of a supper class within a subclass then ,can I access that private method as shown below??? public class Ssupper{ private void setAge(int sAge){ if(sAge >= 100){ System.out.println("You have a long life"); } } class Ssub extends Ssupper{ public static void main(String argv[]){ Ssupper b = new Ssupper(); b.setAge(101); }//End of main } } Thaks Usha
Dave Vick
Ranch Hand
Joined: May 10, 2001
Posts: 3244
posted
0
Sham The first question most peopel will ask you is: Did you try to compile it and see if it works?
Originally posted by Sham Usha: public class Ssupper{ private void setAge(int sAge){ if(sAge >= 100){ System.out.println("You have a long life"); } } class Ssub extends Ssupper{ public static void main(String argv[]){ Ssupper b = new Ssupper(); b.setAge(101); }//End of main } }
In your code you have a couple of other errors to take care of before you can test this: --Ssub is defined within Ssupper, which makes it an inner class. That is fine to do however because it isn't a static inner class you can't have static method in it. You need to move main outside of Ssub or move Ssub outside of Ssuper. --If you move Ssub then you'll have to make it public or the jvm wont find your main method (unless these are just helper classes for some other classes). After you get these taken care of you find that it is giving you an error because setAge is private and can not be accessed outside of Ssupper. Even though it is being accessed by an Ssupper object it is stil being accessed from a class other than Ssupper so it will not compile.
Dave
Dave
Gangi koirala
Greenhorn
Joined: Jul 22, 2001
Posts: 6
posted
0
I understand the errror ,what we wanted to know is when Ssub is a sub class of Ssuper what is the case, So the program changes as below public class Ssupper{ private void setAge(int sAge){ if(sAge >= 100){ System.out.println("You have a long life"+sAge ); } } } class Ssub extends Ssupper{ public static void main(String argv[]){ Ssupper b = new Ssupper(); b.setAge(101);
}//End of main }
Dave Vick
Ranch Hand
Joined: May 10, 2001
Posts: 3244
posted
0
Being a sub class doesn't matter in the case of a private member. Members that are private can only be accessed from with in the same class. If you want to allow access based on relation then you can use protected which will let all subclasses and all classes in the same package access the members. hope that helps you out Dave
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.