Question about overwritten methods in classes that extend each other. - java

I'm studying for a Java-exam and have a question concerning static and dynamic types.
I've got 4 classes: A, B, C and Main.
public class A {
private void tell(){
System.out.println("AA");
}
}
public class B extends A {
public void tell(){
System.out.println("BB");
}
}
public class C extends B {
}
public class Main{
public static void main(String[] args) {
A c = new C();
c.tell();
}
}
My suggestion was: the output should be "BB", because c has the dynamic type C. Since C doesn't have the method "tell" the method of the upper class B is used, which prints "BB".
The outcome however is an error, because Java looks for "tell" in A. In A it of course can't find it, because there it is declared priavte. But why does it look in A, although only it's static type is A, but it's dynamic type is C?

You are getting an error because at compile time, the compiler does not know the actual instance that will be put in A, so when the compiler sees c.tell() he only looks at the class A which indeed does not have an acessible tell() method.
One way to understand this is with this example:
public class A {
private void tell(){
System.out.println("AA");
}
}
public class B extends A {
public void tell(){
System.out.println("BB");
}
}
public class C extends A {
}
public class Main{
public static void main(String[] args) {
A b = new B();
b.tell();
A c = new C();
c.tell();
}
}
You can see that the first 2 lines would be ok (by your current logic of thinking). B has the method tell() so b should be able to call tell(). But using the exact same assignment with another subclass of C which does not have the tell() method then your logic would fail. A nor C have the tell() method so the program suddenly has a call to a method that does not exist or is not accessible.

Related

Overloading subclass with subclass arguments (java)

My code is similar to this:
class Base{
public void handleObject(A a){
//more code...
System.out.println("A");
}
}
class Sub extends Base{
public void handleObject(B b){
//more code specific to this instance and class B
System.out.println("B");
}
public void handleObject(C c){
//more code specific to this instance and class C
System.out.println("C");
}
}
Where B and C inherit from A.
I then want to call handleObject of Base from this code:
//...
Sub s = new Sub();
A[] obj = {new B(), new B(),new C(), new A()};
for(A o:obj){
s.handleObject(o);
}
//...
And I expect Sub.handleObject(B b) to be called for each object of type B, Sub.handleObject(C c) for type C, and Base.handleObject(A a) to be called for objects of type A.
The real result is it prints "A" three times.
Is it possible to make it work using java's overloading capabilities or must I type check every object myself? If not, what is the best practice to achieve the desired behavior?
This question is very similar to mine but the answers only show why his attempts did not work and did not offer a sufficient solution for me.
I have also tried making it work using Visitor Pattern, but in their example it seems like it is required for the Base class (or at least the interface) to know about Sub, which is something I prefer not to have my project.
I suggest you use polymorphism to your advantage. Instead of trying to figure out how to behave for different classes of objects, let each class provide its own behavior:
class A {
public void handleMyself() {
System.out.println("A");
}
}
class B extends A {
#Override
public void handleMyself() {
System.out.println("B");
}
}
class C extends A {
#Override
public void handleMyself() {
System.out.println("C");
}
}
class Base {
public void handleObject(A a) {
a.handleMyself();
}
}
class Sub extends Base {
public static void main(String... args) {
Sub s = new Sub();
A[] obj = {new B(), new B(), new C(), new A()};
for (A o : obj) {
s.handleObject(o);
}
}
}

Java Generics and Inheritance recursion

I came across the following Java code that uses generics and inheritance. I truly do not understand what the following snippet does:
class A<B extends A<B>> {
...
}
What does this code do?
(I got this from DBMaker in MapDB)
It is almost clear and the question actually conists in two parts:
1) why B extends A?
2) why A inside B extends A<B> has generic type B?
Answers for these parts will be:
1) In particular example this class (A) is builder class (called DBMaker), so most of its methods return some type, which extends this builder's class type. This explains, why B should extend A class.
2) But, actualy, if we will hide for the second part ...extends A<B>, we will receive just class A<B>. So A has type variable of type B. That is why in ...extends A<B> A is marked as type A having type variable B.
This tells that A needs derived definitions to be able to do some work:
public abstract class A<T extends A<T>> {
protected T instance;
T getOne() {
return instance;
}
}
public class B extends A<B> {
public B() {
instance = this;
}
}
public static void test() {
B b = new B();
b.getOne();
}
This is most commonly used in interface definitions, where one wants to explicitly use instances of classes implementing an interface in return types or in arguments and not the interface itself:
public interface TimeSeries<T extends TimeSeries<T>> {
T join(T ts);
}
public class DoubleTimeSeries implements TimeSeries<DoubleTimeSeries> {
#Override
public DoubleTimeSeries join(DoubleTimeSeries ts) {
return null;
}
}
So I did some tests to figure this one out, and here is my test cases to see how one could use such a generic case:
public class A<B extends A<B>> {
int x = 10;
B test;
void printX() {
System.out.println(x);
}
void setB(B b) {
test = b;
}
void printB() {
System.out.println(test);
}
}
public class B extends A<B> {
}
public class Run {
public static void main(String[] args) {
A<B> test = new A<B>();
B myB = new B();
test.printX();
test.setB(myB);
test.printB();
myB.printB();
}
}
I hope the code might be self explanatory. If not leave a comment and I will try and explain what is going on. Look at the last line, myB.printB(), here we will get a null, because B has not yet been set for myB, but only for test. This demonstrates that we can have an infinite recursion into classes of B inside A (and inside B for that matter).
we can say:
myB.test.printB();
This will get an error (null pointer), but shows that we now have access to test in the A class from B, and we can go as deep as we want recursively with as many cases as we like. So the A class kind of functions as a wrapper of infinitely many B classes. Does this make sense?
This makes it easier when defining method return types such as this:
class A<B extends A<B>> {
public B getMe(){
return (B) this;
}
}
This tells Java compiler that you are in getMe() method returning a subclass of class A.
class C extends A<C> {
}
C c = new C();
c.getMe(); //returns C

If a class inherits a method does calling that method on that class point to the super class or does it make a local copy within the child class?

Say I have Class A and Class B. Class B extends Class A. Class A has one method.
public class notimportant
{
public void one()
{
}
}
public class A extends notimportant
{
public void one()
{
//assume there is a super class making this call legal which doesnt do anything
super.one();
System.out.println("blah");
}
}
public class B extends A
{
}
A var1 = new B();
if I call 'var1.one();' will the output end up being:
"blah"
"blah"
because it creates a local copy of 'one()' in Class B and then reads that which calls 'super()' which leads it up to method 'one()' in Class A OR does it just print
"blah"
because it knows to look directly at Class A
EDIT: Hope that is a lot more clear now.
It will follow the way you have it currently written:
-> New object of class B
-> Call method One on this object
-> First line calls supermethod, proceed to execute it
-> Second line prints out after that
Your code doesn't compile at all though, you might want to clear that up. What's keeping you from testing this yourself?
Here's the new situation as you described it. Everything still works as expected, you just add a layer.
public class C {
public void test() {
System.out.println("Inside C");
}
}
public class B extends C {
public void test() {
super.test();
System.out.println("Inside B");
}
}
public class A extends B {
public static void main(String[] args) {
A obj = new A();
obj.test();
}
}
Output:
Inside C
Inside B
super means your superclass – it's resolved at compile-time.
It does not mean the immediate parent class of whatever the runtime type of this is.

Java Dispatching-Runtime type

I am confused with method dispatching in java. Why does the first method "a.m1(b)" call to the class A?
The calling variable is a. And its runtime type is B, isn't it?
class A {
public void m1(A a){
System.out.println("A-m1");
}
public void m1(){
System.out.println("A-m1");
}
}
class B extends A {
public void m1( B b){
System.out.println("B-m1");
}
public void m1(){
System.out.println("B-m1");
}
}
public class HelloWorld {
public static void main(String[] args) {
B b = new B();
A a = new B();
a.m1(b);//prints A-m1
a.m1();//prints B-m1
}
}
Overload resolution is done based on compile-time types. A variable of type A only exposes the methods m1() and m1(A). Because you pass in a parameter, m1(A) is invoked; or rather, the appropriate override thereof. Except that m1(B) is not an override of m1(A). (Off the top of my head, I don't know if overrides can widen argument signatures, but they certainly can't narrow them.)

Overriding a Java Method

I'm new to Java, and I've read over some tutorials on overriding methods, but an example I'm looking at isn't working the way I expect. For example, I have the code:
public class A{
public void show(){
System.out.println("A");
}
public void run(){
show();
}
public static void main( String[] arg ) {
new A().run();
}
}
public class B extends A{
#Override
public void show(){
System.out.println("B");
}
}
When I instantiate and call B.run(), I would expect to see "B" outputted. However, I see "A" instead. What am I doing wrong?
Edit: Yes, the classes are in two separate files. They're shown together for brevity.
Edit: I'm not sure how B is being instantiated, as it's being done by a third-party program using a classloader.
Edit: More info on the third-party program. It starts by calling A.main(), which I didn't initially show (sorry). I'm assuming I need to make "new A().run();" more generic to use the name of the current class. Is that possible?
That code will output B if you:
(new B()).run();
Whatever the problem is, it's not in the code you've quoted.
Updated (after your edit)
If the third-party program is calling A.main(), there's nothing (reasonable) you can do in B that will inject itself into A. As long as A.main is doing new A().run(), it's going to have an instance of A, not an instance of B. There's no "current class name" to use, or if there is (depends on your point of view), it's A, not B.
You'll have to get the third-party program to call B in some way, rather than A, or just modify A directly (e.g., getting rid of B entirely). You do not want to modify A to make it use B; that tightly binds it to a descendant and makes the separation between them largely pointless.
Hope that helps.
I tried, putting your two classes in two files, and it worked nicely, outputting "B". I called :
B b = new B();
b.run();
UPDATED : Also works as (because it is the same runtime instance):
A a = new B();
a.run();
Works for me.
Here's my code for A and B:
package so;
public class A{
public void show(){
System.out.println("A");
}
public void run(){
show();
}
}
class B extends A{
#Override
public void show(){
System.out.println("B");
}
}
Here's my entry point:
package so;
public class EntryPoint {
public static void main(String[] args) {
B b = new B();
b.run();
}
}
It prints out 'B'.
It depends of instantiating. Try this:
A v1 = new A();
A v2 = new B();
B v3 = new A();
B v4 = new B();
v1.run()
v2.run()
v3.run()
v4.run()
I tried your example and my output was B.
How are you instantiating? Here's the exact code I ran.
public class Test {
public static class A {
public void show() {
System.out.println("A");
}
public void run() {
show();
}
}
public static class B extends A {
#Override
public void show() {
System.out.println("B");
}
}
public static void main(String args[]) {
A a = new B();
a.run();
}
}
If your external program instantiates A, you will have A, not B.
But you can try something like this, using some reflection, and pass "com.mypackage.A" or "com.mypackage.B" as arguments to your program.
With this code (exception catch missing), you will be able to print "A" or "B" depending on the string parameter that you pass.
public static void main( String[] arg ) {
String className = arg[0];
Class myClass = Class.forName(className);
Constructor cons = myClass.getConstructor(new Class[0]);
A myObject = (A) cons.newInstance(new Object[0]);
myObject.show();
}

Categories

Resources