If I have a class, class Animal.
And I have a class Dog and a class Cat both inheriting Animal.
Cat can call methods inside Animal. But can Cat call methods of Dog?
If I have a class, class Animal.
And I have a class Dog and a class Cat both inheriting Animal.
Cat can call methods inside Animal. But can Cat call methods of Dog?
in javascript , yes , i'll use coffeescript because it is easier to write :
Does it make sense ? probably not, but in javascript methods of a prototype are not bound to an object(unless you force it with closures). Now one could argue javascript doesnt have classes like java , but are C++ classes like Java ones ? python classes like Java ones ? who decides what's a real class or not ?
My point is the question is irrelevant outside of a language context.
No it can not and no it should not (at least not when talking about proper OOP). If a cat really needs a dog (for whatever sick reason) you should inject the dog in the cat. If you think you need it you probably have the wrong inheritance / abstraction.
Above is an example of injection. Note that as Tony Hopkinson stated you are calling the methods on the instance of dog in this case. You could call methods on the class if they are
public static
, but since it is tagged OOP you really shouldn't. P.S. example is in PHP.In java context [I have come across OOPs via Java]
No you cannot.
The methods that can be called by an object is determined by the reference variable.
If you use Dog/Cat reference variable it can only access methods in Dog/Cat class(including inherited and overridden ones)
If you use Animal(i.e.Parent Class) as a reference variable and have it refer to a Cat/Dog class object. You can only call the inherited/overridden methods of subclass using that reference variable.This is decided at compile time.[if the fn being called is identified by the reference variable or no]
The Dog class object is unaware of exclusive Cat class functions[other than inherited and overridden ones] so it cant call the methods.
As pointed by others, If u have a case as such u might not be looking for inheritance.
The answer to your question can be answered by stating it like this Is a cat a dog?
I'll let you answer this one.
Here cat and dog are two distinct classes and there is no direct relation between them.If we wish we can add few codes to link these classes. Until then the members in one cannot be accessed from the other.
If Cat doesn't inherit from Dog then no