java - Trying to call child method, but instantiated it as parent -


i've tried searching answer this, couldn't find answer exactly... here's situation. have class , subclass, , defined them this:

public class shape{    public methoda{      system.out.println("hello!");   } }  public class square extends shape{    public methodb{      system.out.println("i'm square!);   } } 

at main, instantiate them unable call methodb because "gave" (not sure of terminology here) type shape:

shape square = new square(); square.methodb() // doesn't work. 

did design wrong if wanted able call child class' methods? i'm doing way because have many shapes inheriting shape class, didn't want import every single shape class project. tried searching, didn't find answer in way understood it. thanks.

-rb

you need decide want.

the point of polymorphism can abstract away details specific implementation programming in common (interface or base or abstract class).

did design wrong if wanted able call child class' methods

i don't know intent, not. if want able call child class' methods in particular case, change reference type

square square = new square(); square.methodb() // doesn't work. 

if in general want able call methodb on shape anywhere, need define methodb in shape itself, not square.

public class shape{    public void methoda{      system.out.println("hello!");   }    public abstract void methodb(); }  public class square extends shape{    public void methodb{      system.out.println("i'm square!);   } } 

now shape guaranteed have methodb method.

the key remember when instantiate object, reference type 1 carried on. when calling shape s = new square(), compiler uses square constructor. once called, forgets knowledge being square because told so. therefore, s.methodb() won't compile because compiler doesn't know if s square, circle, triangle, etc. told forget.

if there squares can used on square, calling code needs use square class , not shape.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -