Moving a reference variable in Java

I have something incomprehensible regarding referencing a reference variable in Java.

I have two classes A and B. A is the superclass of B. If I have two objects, then the print statement:

A a = new A(); //superclass

B b = new B(); //subclass

System.out.println ((A)b);

what exactly happens when the println method is executed?

I know that since B is a subclass of A, I am allowed to do the following:

A a2 = (A)b;

I also know that when println takes a reference variable as an argument, the toString () method of the class that created the argument object is invoked (implicitly). This is because the println () method looks for an argument of type String, and the toString () method represents the object as a string. And even if we do not write toString (), the method is called - implicitly. So, the following two statements are equivalent:

System.out.println (b);

System.out.println (b.toString());

, : ,

System.out.println ((A)b); 

?

, b B A. - ,

B b = new B();

b . ? : b , , , ?

.

+3
8

.

System.out.println(XXX) ( ), , . Java toString(), toString , , .

, Java , - , . B () . ( ) - B. , B.

+4

PrintStream println(...) ( System.out).

:

void println(String x)
void println(Object x)

println((A)b), println(Object), A String ( , println). println(b.toString()), println(String), .

b A , println() A B. - ( ), , , , , , , .

:

A a2 = (A)b;

, B A. , ( , , , ).

B , . B:

class B extends/implements A {...}
B b = new B();   // construct a B
A a = b;         // assign a B to an A variable, it superclass
A a = (A) b      // as above including check to see that b is an A (redundant, may be optimised away).

B b = a;         // Syntax error, won't compile
B b = (B) a      // Will check whether a is of type B then assign to variable b

, b A, , a b, . , a , //is A b, ClassCastException.

B ( "B" -ness), (instance-) , , B , , A B.

, , , .

, , B b_only(), a.b_only(); ((B)a).b_only(), .

+3

?

. A. "b" B.

: b , , , ?

. :

class Foo {
    public static void main(String[] args) {
        B b = new B();
        assert "B".equals(((A) b).m());
    }
}

class A {
    String m() { return "A"; }
}

class B extends A {
    String m() { return "B"; }
}
+1

Java , . , . [ , - ]

+1

, (B ). , ... - , B, A. A, , , - , , B - .

, - A, , , B.

+1

, java , . , , . Ex -

Interface X {
 public abstract void xx();
 public abstract void yy();
}

Class XXX implements X {
   ...........
}

Class XY extends XXX {
  X xy = new XXX();
} 

xy X XXX .

, , , .

+1

, , - , . toString , , .

, , . . , java- , .

. .

0

: b , , , ?

b; , ;

, ():

, = 6'2 "

- , height , ; 6 '

, Son , i.e 6 '.

0

Source: https://habr.com/ru/post/1702508/


All Articles