Java - duda con instancia de clase heredada

 
Vista:
sin imagen de perfil
Val: 19
Ha disminuido su posición en 3 puestos en Java (en relación al último mes)
Gráfica de Java

duda con instancia de clase heredada

Publicado por Raul (8 intervenciones) el 25/01/2018 16:33:41
Alguien me puede decir porque en este código donde hago una instancia de clase heredada con
1
A b = new B();
recibo como valor el atributo de la clase hija:

A.java
1
2
3
4
5
public class A {
    public void printValue(){
        System.out.println("A");
    }
}

B.java
1
2
3
4
5
public class B extends A {
    public void printValue(){
        System.out.println("B");
    }
}

Test.java
1
2
3
4
5
6
public class Test {
    public static void main(String... args) {
        A b = new B();
        b.printValue();
    }
}

en cambio en este código donde vuelvo a hacer una instancia de clase heredada con
1
A b = new B();
recibo como valor el atributo de la clase padre:

A.java
1
2
3
4
5
6
7
8
9
10
public class A {
    public static void value(String y) {
        System.out.println("A");
    }
    public static void main(String[] args) {
        A b = new B();
        String x = "B";
        b.value(x);
    }
}

B.java
1
2
3
4
5
public class B extends A{
    public static void value(String x) {
        System.out.println("B");
    }
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil
Val: 349
Bronce
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

duda con instancia de clase heredada

Publicado por Andrés (340 intervenciones) el 30/01/2018 20:58:00
https://docs.oracle.com/javase/tutorial/java/IandI/override.html

Overriding and Hiding Methods



Static Methods

If a subclass defines a static method with the same signature as a static method
in the superclass, then the method in the subclass hides the one in the superclass.

The distinction between hiding a static method and overriding an instance method
has important implications:

- The version of the overridden instance method that gets invoked is the one in the subclass.
- The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar