user3743026
user3743026

Reputation: 1

I do not understand something about Java Inheritance

It Does Not Work, and i don't know why... I'm new in java world.

public class Mixed2 {
    public static void main(String[] args) {
        A c = new C();
        c.m1();
        c.m2();
        c.m3("My text");
    }
}
class A {
    void m1() {
        System.out.print("A's m1, ");
    }
}
class B extends A {
    void m2() {
        System.out.print("B's m2, ");
    }
}
class C extends B {
    void m3(Object text) {
        System.out.print("C's m3, " + text);
    }
}

Mixed2.java:5: error: cannot find symbol
        c.m2();
         ^
  symbol:   method m2()
  location: variable c of type A
Mixed2.java:6: error: cannot find symbol
        c.m3("My text");
         ^
  symbol:   method m3(String)
  location: variable c of type A
2 errors

is because A don't have m2 and m3 methods?If i put in A m2 and m3 it works, but B m2 and C m3 are called. I do not understand.

Upvotes: 0

Views: 99

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285401

  1. There's no use of polymorphism in your code.
  2. Your variable is an A variable, and thus the m2 and m3 methods do not exist for this type, and can't be used without casting, which defeats the purpose of OOP.

I would rename method m2() in B to m1(), and then you'll get true polymorphism:

class B extends A {

    @Override
    public void m1() {
        // do you want to call the super's method here?
        // if so, then call
        // super.m1();

        System.out.print("B's m1, ");
    }
}

Class c's m3 method requires a parameter, and so polymorphism won't work for it as its signature cannot match that of m1's.


Edit
You ask in comment:

sorry is about Inheritance and . i dont know ... is a reference of type A who keep an object of type C ... then c should have idea about the m3?

Your c variable is an A type variable that references a C object. Only A methods will be available to that variable unless you explicitly cast it to something else:

((C)c).m3("foo");

Which is brittle and ugly code. If you want to demonstrate polymorphism, then your child class method should override a parent method.

Upvotes: 4

McLovin
McLovin

Reputation: 3674

Although you constructed an object of type C, the reference to the object is of type A.
You can do this because C is a subclass of A, but you can only access methods that are declared in A.

Upvotes: 1

Related Questions