OOP - Inheritance - oop

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?

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.

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.
class Animal
{
public annoy();
}
class Cat extends Animal
{
private $dog;
public function __construct(Dog $dog)
{
$this->dog = $dog;
}
public function annoyDog()
{
$this->dog->annoy();
}
}
class Dog extends Animal
{
}
$dog = new Dog();
$cat = new Cat($dog);
$cat->annoyDog();
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.

The methods defined in a superclass are accesible to any subclass. But "sister" classes cannot access the (private) methods of one another.
So if your classes Cat and Dog inherit from Animal, then both Cat and Dog objects can call methods from Animal, but they cannot (must not) access the methods of each other.

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 :
class Animal
bark:-> "i'm an animal"
class Dog extends Animal
eatBone : -> "i'm eating a bone"
class Cat extends Animal
cat = new Cat
alert Dog::eatBone.call cat
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.

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

I'm afraid that... no. Cat cannon invoke Dog methods.
Inheritance allows to "view" parents (public/protected if you are using Java) methods inside child classes, but not inside siblings classes.
Obviosly if Cat has an instance of Dog as property (I don't know why it should have...) it can call public methods of that Dog instance.

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.

Related

How to change object display depending on type?

I though I was ok with POO, but right now I'm all confused with the following.
Basic model
For instance, let's say you've created Dog and Cat objects that extends the abstract class Animal.
abstract Animal has the generic properties:
color: string
legs: number
Cat extends Animal has the extra property:
humansTolerance: number
Dog extends Animal has the extra property:
ballsRetrieved: number
Problem
Now, I want to display a list of all the animals on my application in a generic way. Simple, the application just pulls all the Animal objects from the database, puts them in a nice List<Animal> with each object instantiated with its proper class.
But now, when I click on one given animal, I want to be able to display the Animal generic properties AND the properties that are specific to its type.
For example, If the selected animal is a cat, I want the UI to show the generic animal properties color and legs, but I also want to display the cat property humansTolerance. Same goes for the dog with ballsRetrieved.
Question
Am I supposed to use the often called infamous instanceof / typeof to do that? How can I make the UI display various elements depending on the type of the object?
Use a virtual method or the Visitor Pattern.
The obvious object-oriented approach would be to just have a display() method in the objects. Each "class" displays itself:
class Dog {
...
public display(): void {
...
}
}
I don't know what is "customary" in TypeScript, but the object-oriented approach would hide properties, and offer behavior instead.

Difference between a child of a class and an instance of a class?

What's the difference between the child of a class and an instance of a class? Both seem to inherit code from their "parent". Is the difference that an instance of a class is executed code, versus a child of a class merely being around to create additional instances?
A class is nothing more than a definition, a template, a pattern. An instance of that class is a copy of that definition that has been allocated memory space in which to hold its data. It's like saying a cake is an instance of a cake recipe.
A child of a class is literally that - the parent forms a base definition, which the child then extends or enhances. It's a variation on the parent, much like a chocolate cake is a variation (or it extends) a basic cake recipe.
Note that this very simple explanation of OO concepts hides how this stuff is actually implemented at the machine level. A class can contain methods (operations) - there is only one copy kept of these methods, instantiating a new instance of the class doesn't make a fresh copy of the methods. Instead memory space is allocated to the new instance, and pointers will be used to point to the actual code that should be implemented for each method. Each instance does have its own copy of data (attributes) though.
For example with php:
class A {
//...
}
class B extends A {
//...
}
$a = new A();
We say B is the child of A, $a is an instance of A.

What is the difference between polymorphism and duck typing?

I'm a little confused with the two terms, here's what I know:
Polymorphism is the ability of object of different types to be handled by a common interface. While duck typing, is a kind of dynamic typing that allows objects of different types to respond to the same methods.
From what I understand, polymorphism is more about creating an interface that can be shared across different classes. And duck typing is about loose typing that will allow methods to be called as long as it is found on the receiver of the message.
Is this correct? I'm pretty confused on the two, they seem related but I do not know what their relationship is. Thanks a lot in advance!
Polymorphism (in the context of object-oriented programming) means a subclass can override a method of the base class. This means a method of a class can do different things in subclasses. For example: a class Animal can have a method talk() and the subclasses Dog and Cat of Animal can let the method talk() make different sounds.
Duck typing means code will simply accept any object that has a particular method. Let's say we have the following code: animal.quack(). If the given object animal has the method we want to call then we're good (no additional type requirements needed). It does not matter whether animal is actually a Duck or a different animal which also happens to quack. That's why it is called duck typing: if it looks like a duck (e.g., it has a method called quack() then we can act as if that object is a duck).
So are these related? They are simply separate features that a programming language may have. There are programming languages which have polymorphism but that do not have duck typing (such as Java). There are also languages that have polymorphism and duck typing (such as Python).
This is an example for Polymorphism in Python.
class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
def talk(self): # Abstract method, defined by convention only
raise NotImplementedError("Subclass must implement abstract method")
class Cat(Animal):
def talk(self):
return 'Meow!'
class Dog(Animal):
def talk(self):
return 'Woof! Woof!'
animals = [Cat('Missy'),
Cat('Mr. Mistoffelees'),
Dog('Lassie')]
for animal in animals:
print(animal)
print(animal.name + ': ' + animal.talk())
This is an example for duck Typing in Python.
class Duck:
def quack(self):
print("Quaaaaaack!")
def feathers(self):
print("The duck has white and gray feathers.")
def name(self):
print("ITS A DUCK NO NAME")
class Person:
def quack(self):
print("The person imitates a duck.")
def feathers(self):
print("The person takes a feather from the ground and shows it.")
def name(self):
print("John Smith")
def in_the_forest(duck):
duck.quack()
duck.feathers()
duck.name()
def game():
for element in [Duck(), Person()]:
in_the_forest(element)
game()
In polymorphism we see subclass (Cat and Dog) inheriting from the parent class (Animal) and overriding the method Talk.
In case of duck typing we don’t create a subclass instead new class is created with method having same name but different function.
Short Answer:
Duck typing is one way of achieving Polymorphism.
Another way is by using static typing.
Long Answer:
There are two different concepts involved here, typing and programming technique.
Duck typing is a type of typing. And typing means when to throw error when an object passed around isn't what is expected. Duck typing is a kind of typing where it throws error when the program is running and the method being called isn't available. Static typing comes with compile time checking, so if the type info doesn't match, it will throw error when you compile the code. And that is typing.
Polymorphism is a programming technique where you allow multiple types of object to fulfill certain responsibilities. You can do that by using a base type to represent all the child class types. You can use duck typing to represent all the different types that have the needed methods. You can use an interface to represent all the types that implement the interface.
There are answers saying polymorphism is inheritance, and that is not correct. Although you can use inheritance to create polymorphic behavior and usually that's what you do, but that's not what polymorphism is about.
For one, you don't need inheritance to have polymorphism as described above.
Secondly, the term "Polymorphism" is more meaningful in the context of the client code that depends on abstraction, and not the implementation code. Just because you have a super class and a few other classes that inherit from it and overriding some methods does not mean it's polymorphism, to create polymorphism you have to write client code in a polymorphic way to consume these classes.
Two type Polymorphism
Method overloading(Compile time Polymorphism ).
Method overriding(Run Time Polymorphism ).
Method overloading :- same function name and different data type is known as Method overloading
Example :
int addTwovalues(int a, int b)
{ return (a+b)}
float addTwovalues(float a, float b)
{ return (a+b)}
Method overriding :- same function name and same data type but different Class
is known as Method overriding.
class a
{
virtual int addtwovalues()
{ // to do }
}
class b:a
{
override int addtwovalues()
{ // to do }
}
a obj=new a();
obj.addtwovalues();
b objb=new a();
objb.addtwovalues(); //run time Polymorphism

How to decide whether use IS A or HAS A Relation

public class B {
public String getMe()
{
return "Some";
}
}
Assume that i have a above class , by which parameters should we decide what to use ?? Whether is a or Has a Relation ??
HAS - A
public class A {
public static void main(String args[])
{
B b = new B();
System.out.println(b.getMe());
}
}
or
public class A extends B
{
public static void main(String args[])
{
A b = new A();
System.out.println(b.getMe());
}
}
Depends on the logical relation. It just needs to make sense.
Example:
Lets say you have Animal classes.
So you have these classes: Animal, Dog, Cat , Leopard, Fur, Feet
Cat and Dog IS A Animal.
Leopard IS A Cat.
Animal HAS A Fur, Feet.
In a nutshell:
IS A relationship means you inherit and extend the functionality of the base class.
HAS A relationship means the class is using another class, so it has it as a member.
There are 4 types of relations possible :
Generalization (IS A) : Which is implemented using inheritance like you did above. It's used when class A has all the same feature of B and you want to add some more features. So you simply extend B and add the new features.
Aggregation (HAS A) : This is a bit weaker relation than generalization. You use this relation when the object of A owns objects of B or is composed of objects of B (may be among other objects of other classes). The first type is called shared aggregation, the second is called composition. In aggregation and composition there usually an object controlling the life of the other object (it instantiates it and destroys it as it needs).
Association: In association, the classes simply know about each other's so it's weaker than aggregation. The objects do not control each other's life.
Usage : It's the weakest relation of two classes and it means simply that one class may appear as a type in a method parameter or is used internally in code.
In your example, it should be aggregation (HAS A) if A has a field of type B. But if it just creates instance of B to be used in code internally and the object is disposed from memory when the scope ends then it's neither IS A nor HAS A. It's just a usage relation.
In simple term:
"is a" represent the inheritence/extends
"has a" represents the delegation/association
for example:
House is a Building (inheritance)
House has a door(s) (association)
Here is one of the best resources I used for understanding OOP: http://chortle.ccsu.edu/CS151/cs151java.html (part 6 & 10)
is-a is like for example, a Dog is an Animal or a Cat is an Animal or It is like "a person is that-kind of a person". Is-a relationships have other objects' properties, like here "Animal" is a class(object) and etc.
The has-a relationship is like, an object has its own properties, for example, Fish has Gills or pants have pockets ... something like that.

Data Mapper: Is my interpretation correct?

I'm trying to confirm now, what I believe about the Data Mapper pattern. So here we go:
Section A:
A Data Mapper is a class which is used to create, update and delete objects of another Class. Example: A class called Cat, and a Data Mapper called CatDataMapper. And a database table called cats. But it could also be an xml file called cats.xml, or an hard-coded array called cats. The whole point of that Data Mapper is to free the Business Logic which uses the Cat class from thinking about "how to get an exisiting cat", or "how to save a cat", "where to save a cat". As a user of the Data Mapper it looks like a blackbox with well-defined methods like getCat(int id), saveCat(Cat catObject), deleteCat(Cat catObject), and so on.
Section B:
First I thought it would be clever if Cat inherits from CatDataMapper, because calling such functions then is a bit more convenient. For example, methods like catWithId(int id) could be static (class method) and return an instance of a Cat, initialized with data from anywhere. And when I work with a cat object in my code, I could simply call myCat->save(); to store it whereever the Data Mapper will store it (don't care where and how, the Data Mapper hides this complexity from the user).
In conclusion, I'm a little bit confused now ;)
Do you think that Section A is valid for the Data Mapper pattern? And if I would do it additionaly as described in Section B, would that be bad? Why?
I think your Section A corresponds to the definiton of the Data Mapper pattern as given by Martin Fowler
Be careful with the details of your implementation language. In Section B having catWithId() be a static member of the cat class may interfere with polymorphic behavior of the method.
In java, the JVM will dispatch a static method based on the declared type of the reference.
Try this out:
1. create a class CatDataMapper with the static method catWithId(int id)
2. create a class Cat extending CatDataMapper that has the desired Business Logic behavior
3. subclass Cat with LoggedCat that logs all activity, including the activity from CatDataMapper
4. do Cat foo = new LoggedCat()
5. do Cat bar = foo.catWithId(5)
note which method is called, it should be the static method of CatDataMapper not the static method of LoggedCat
http://faq.javaranch.com/view?OverridingVsHiding gives a more in-depth discussion of this.
I think this is an OK approach. Aside from the naming conventions used, you're following a well known Data Access pattern here and you're allowing the users of the Cat objects to perform CRUD operations without having to talk to the CatDataMapper which is always a plus in my book.
I would usggest looking at Spring Container technology for this if you're in the java world.