This week's book giveaway is in the JDBC forum. We're giving away four copies of SQL Antipatterns: Avoiding the Pitfalls of Database Programming and have Bill Karwin on-line! See this thread for details.
class Super{ private void Hello(){ System.out.println("Iam in Super()"); } } class Sub extends Super{ private void Hello(){ System.out.println("Iam in Sub()"); } } public class Checking{ public static void main(String[] args) { Super s = new Sub(); Sub s1 = new Sub();
s.Hello();//iam getting error why ? s1.Hello();this is Correct
} }
here iam calling Super class ref s.hello()on Sub class Obj. Iam geting compile time error why ?What is the reason..
I Wayan Saryada
Ranch Hand
Joined: Feb 05, 2004
Posts: 41
posted
Both line in your main method should give a compile time error because you cannot call a private method from outside its class.
For other notes, the Sub class is not overriding the Super class Hello method because we cannot override a private method. [ January 02, 2008: Message edited by: I Wayan Saryada ]
class Super{ private void Hello(){ System.out.println("Iam in Super()"); } } class Sub extends Super{ void Hello(){ System.out.println("Iam in Sub()"); } } public class Checking{ public static void main(String[] args) { Super s = new Sub(); Sub s1 = new Sub();
s.Hello();//iam getting error why ? s1.Hello();this is Correct
} }
here iam calling Super class ref s.hello()on Sub class Obj. Iam geting compile time error why ?What is the reason..
Jesper Young
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 8683
posted
Why are you repeating the question? I Wayan Saryada already gave you the answer.
The variable 's' is of type Super. That means that if you call a method on it, it will only look in class Super, even when 's' really refers to a Sub object. Because the method is private in class Super, you can't call it on s.
Also, private methods cannot be overridden. A private method is only visible in the class in which it is declared. It is not visible in subclasses. The subclass doesn't know what private methods exist in its superclass, so it can't override private methods in the superclass. You should see the hello() method in class Sub as a new method that's totally unrelated to the hello() method in class Super. [ January 03, 2008: Message edited by: Jesper Young ]
Originally posted by Jesper Young: Why are you repeating the question?
Jesper, i could see that he changed the program in such a way that method Hello() in subclass having default access modifier and NOT private as in his original post.