+ 2

How to call parent class method with child class object when method name are same

Class a { Void print (){ syso("class a method"} } Class b extends a{ Void print (){ syso("class b method"} } Class c { Public static void main() { // How to print here "class a method with class b object" }

9th Jun 2019, 10:30 AM
shivam
shivam - avatar
6 ответов
+ 3
in my opinion, there is no pure syntax for call overridden Parent.method() from outside of child class. But you can overload print() method to call super.print() or write another method to do it class A { void print() { System.out.println("class A method"); } } class B extends A { void print() { System.out.println("class B method"); } void print(boolean parent) { super.print(); } void printA() { super.print(); } } class C { public static void main(String[] args) { // How to print here "class A method with class B object" boolean parent = true; B b = new B(); b.print(parent); b.printA(); } } better situation is for variables, there you can do B b = new b(); A a = b; System.out.println(a.variable);
9th Jun 2019, 5:06 PM
zemiak
+ 11
Like this : b B; B::a.print();
10th Jun 2019, 4:42 AM
Manoj
Manoj - avatar
+ 2
super.print() is a statement called from subclass print() method This statement must be the first statement This is the concept of overriding In the above mentioned code since it is an instance method we can able to use the super keyword if it is static method it will not support since super is non static a non static cannot be called directly from static method code will get compile time error if it is final. final methods cannot be overridden error will raise
10th Jun 2019, 7:02 PM
sree harsha
sree harsha - avatar
+ 1
Thanks for your and but super keyword can't be used with object in java
9th Jun 2019, 12:33 PM
shivam
shivam - avatar
0
I would try: b.super.syso(); But I am not really sure how it works in Java, but I hope this lesson would help you: https://www.sololearn.com/learn/Java/2163/
9th Jun 2019, 12:11 PM
Seb TheS
Seb TheS - avatar
0
unfortunately operator :: not works here in java is :: used as abbreviation in expressions with parameters, like lambda expressions. b::print is abbreviation for (s -> b.print(s) ) import java.util.stream.Stream; class A { void print(String str) { // parameter is necessary System.out.println("class A method, "+str);} } class B { void print(String str) { System.out.println("class B method, "+str);} } class C { public static void main(String[] args) { B b = new B(); Stream.of("aaa","bbb","ccc") .forEach( b::print ); } } /* output: class B method, aaa class B method, bbb class B method, ccc */ for b it is not calls Parent.method() but child method
10th Jun 2019, 11:33 PM
zemiak