Ask your own question, for FREE!
Computer Science 16 Online
OpenStudy (anonymous):

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(); } }

OpenStudy (konradzuse):

what is your error? I'm assuming because you did protected void sayHI() the protected rights might not be significant for a child.

OpenStudy (anonymous):

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.

OpenStudy (anonymous):

thanks ... that's really helpful :)

OpenStudy (konradzuse):

Hmmm never seen it that way before.

OpenStudy (konradzuse):

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.

OpenStudy (anonymous):

i see

OpenStudy (konradzuse):

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.

OpenStudy (konradzuse):

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(); } }

OpenStudy (konradzuse):

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.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!