I was reading one piece of code in Java and one function definition caught my eye. Its a long piece of code so I am just putting a abstract version to know how it worked.
Consider I have a file A.java with below code.
abstract public class A
{
public B method1()
{
.....
}
void method2() {};
}
Now I have file B.java with below sample contents
public class B extends A
{
.....
}
Now I am a beginner in Java but from what I have learned that I can call method2 in class B since it extends A. But how can I have return value of a class B in parent class A defined as return value of function method1. Please help me in clearing this concept. I am totally bounced over this piece of code.
Here's the code you posted (edited slightly to tidy it up, but the structure is the same):
abstract public class A {
public B method1() { ... }
void method2() {};
}
public class B extends A {
...
}
You asked this question:
how can I have return value of a class B in parent class A defined as return value of function method1?
Specifically, you are asking how "method1()" on class A can return B, when B itself is a class which extends A:
abstract public class A {
public B method1() { ... }
The reason this works is that the return type of method1()
– and in general, any method defined in class A – has nothing to do with the class structure of A or B.
The return type simply means if you call method1()
:
It does not say anything about how (or even if ) B relates to A.
Methods can specify any return types (so long as that type is valid.. you can't just return things which don't exist). Here's a simple edit of class A showing a few other return types. These additional return types are clearly unrelated to class A – String and List<Integer>
.
abstract class A {
abstract public B method1();
abstract public String method2();
abstract public List<Integer> method3();
}
In this new "A", all it says is:
List<Integer>
It's fine if B itself is defined in terms of A ( class B extends A
), or is altogether defined as a separate class. Here's a version of B, but without "extends A", so it's just a standalone class definition, this would work fine with your definition of A, too.
class B {
}
Here are a few snips from the Java Tutorials about method definitions:
The only required elements of a method declaration are the method's return type, name, a pair of parentheses, (), and a body between braces, {}.
and also:
The return type—the data type of the value returned by the method, or void if the method does not return a value.
There's an additional section possibly worth reading - Returning a Value from a Method – which has more discussion about how this works, what's allowed, etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.