code in java: why this is error? public class Parent { protected void sayHi() { System.out.print("Hi"); } class Child extends Parent { public void sayHello() { System.out.print("Hello"); } } public static void main(String[]args){ new Child().sayHi(); } }
what is your error? I'm assuming because you did protected void sayHI() the protected rights might not be significant for a child.
See the code below: // this is the Parent class public class Parent { protected void sayHi() { System.out.print("Hi"); } // this is an innerclass ok and it inherits from the outerclass Parent class Child extends Parent { public void sayHello() { System.out.print("Hello"); } } } the main method will be like this: public static void main(String[] args) { Parent x = new Parent(); // instantiating a Parent object x Parent.Child y = x.new Child(); // then we instantiating a Child object y using x y.sayHi(); // calling the sayHi() method } I hope this was useful if I'm wrong correct me. thanks.
thanks ... that's really helpful :)
Hmmm never seen it that way before.
I know extending the Rectangle class you will get it's methods; however I also know that you cannot access protected methods from other classes. Change protected. I have done Rectangle2D.Float = new Rectangle2D.Float before.
i see
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html hmm apparently it should work though... Maybe it was because mine wasn't a subclass.... HMm not too sure then.
Okay so I plugged in the code into my IDE and I got a static reference issue. This code works: import java.util.Scanner; /** * * @author Konrad */ public class JavaApplication12 { protected void sayHi() { System.out.print("Hi"); } static class Child extends JavaApplication12 { public void sayHello() { System.out.print("Hello"); } } public static void main(String[]args) { Child c = new Child(); c.sayHi(); } }
The issue was that the child class wasn't static... Not 100% sure on how and where statics are used, but I've never seen this issue... never really did nested classes much either though.
Join our real-time social learning platform and learn together with your friends!