+ 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" }
6 Antworten
+ 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);
+ 11
Like this :
b B;
B::a.print();
+ 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
+ 1
Thanks for your and but super keyword can't be used with object in java
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/
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