Vererbungsproblem

  • Themenstarter sizedoesnotmatter
  • Beginndatum
Status
Nicht offen für weitere Antworten.
S

sizedoesnotmatter

Gast
Hallo an alle die noch zur späten Stunde diese Nachricht lesen!

Ich versuche gerade nachzuvollziehen warum folgender Code nicht das Ergebnis "Klasse B" ausspuckt ...

Code:
public class A {
   
   String test = "Klasse A";
   /** Creates a new instance of A */
   public A() {
   }
   
   public void druckeMessage() {
      System.out.println(test);
   }
}


public class B extends A {
   
   String test = "Klasse B";
   
   /** Creates a new instance of B */
   public B() {
   }
}


public class C{
   
   public static void main(String[] args) {
      A instance_A = new A();
      B instance_B = new B();
      
      instance_A.druckeMessage();
      instance_B.druckeMessage();
   }
}

Die ganze Zeit vor diesem Bsp bin ich davon ausgegangen, dass die Methode druckeMessage aus Klasse A auf Klasse B vererbt wurde und somit auch in Klasse B implizit vorhanden ist. Das Ergebnis lässt allerdings an meiner Theorie zweifeln ???:L

CU
 

André Uhres

Top Contributor
Obschon B die Methode druckeMessage() benutzen kann, befindet sie sich physisch immer noch in A.
Da A nichts von dem String test in Klasse B wissen kann, wird nur der String test aus der Klasse A gedruckt.
B kann aber diesen String problemlos anpassen:
Code:
class B extends A {
    
//    String test = "Klasse B";
    
    /** Creates a new instance of B */
    public B() {
        test = "Klasse B";
    }
}
 
S

sizedoesnotmatter

Gast
Leroy42 hat gesagt.:
Oder eine andere Erklärung:

Nur Methoden können überlagert werden, keine Instanzvariablen.

Führt deswegen auch die Änderung von

Code:
System.out.println(test);

zu

Code:
System.out.println(this.toString());

zu unterschiedlichen Ergebnissen?

Gruß
 

André Uhres

Top Contributor
sizedoesnotmatter hat gesagt.:
Nur Methoden können überlagert werden, keine Instanzvariablen.
..Führt deswegen auch die Änderung .. zu
Code:
System.out.println(this.toString());
zu unterschiedlichen Ergebnissen?
Eigentlich nicht. Die Ursache ist eher folgende:
java.lang Class Object hat gesagt.:
public String toString()

Returns a string representation of the object.
In general, the toString method returns a string that "textually represents" this object.
The result should be a concise but informative representation that is easy for a person to read.
It is recommended that all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the class
of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation
of the hash code of the object.

In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Returns:
a string representation of the object.
 
Status
Nicht offen für weitere Antworten.
Ähnliche Java Themen

Ähnliche Java Themen


Oben