0

for example,

Vector stack = new Stack(); // why are Stack class methods not available even while creating run time object as stack

stack.push(2); // error saying no method found

//vector is a parent reference ...according to polymorphism this must be true right..?

  • 1
    If you define it as a `Vector`, you can use it as a vector and not as a Stack. – dan1st May 06 '20 at 16:39
  • You should some tutorial about inheritance and variable casting – jhamon May 06 '20 at 16:40
  • When you declare a variable to be of a super class then it will be a superclass type and you can use it as such and nothing else. Stack knows about Vector but Vector does not know about Stack. – Joakim Danielson May 06 '20 at 16:43
  • @JoakimDanielson: your phrasing is wrong. It's not "a superclass object", because the **object** is still a `Stack`. It's the **variable** that is of type `Vector`. That exact distinction is very important, as it's at the hearth of this misunderstanding. – Joachim Sauer May 06 '20 at 16:45

3 Answers3

0

A object = new B() , the B is a sub class of A , when you run a class method of the object , it will be searched first on the class A , and if its found , it will be seen in the class B if its declared with a different corps , so if you wanna run a method that is contained only in class B you have to do this : B object = new B() , or you can declare it in the class A but without corps , something like this :

public class Vector { 
...
public static void push() {}
}
Karam Mohamed
  • 843
  • 1
  • 7
  • 15
0

Vector stack defines a variable of type Vector. Then you initialize it with something.

The type of the variable is still Vector, no matter what you initialized it with.

Therefore the compiler won't let you do anything that Vector can't do (and Vector doesn't have a push method.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
0

You can assign an object of child class to a reference of parent class because child inherits properties of a parent. Hence calling a method of a parent you can be sure the call will be properly "dispatched" to the implementation of the child (if it overrides the parent implementation).

But you can't call the method that does not exist in parent using the reference of parent type .

Alexey R.
  • 8,057
  • 2
  • 11
  • 27