Difference between a parent class and super class - oop

Is there any difference between a parent class and a super class? Is a super class simply a parent class that doesn't inherit from other classes?

This is more of a terminology difference, the idea of parent and child classes or super and subclasses. It seems to depend on programming language experience and application domain as to which one you use as well as when you first began getting into Object Oriented Programming.
In both cases there is a class, the parent class or super class or base class, from which is derived other classes, the child class or subclass. The child class or subclass extends the parent class or super class by adding some capability to the existing capability of the class being extended.
super() is how the parent or super class constructor for a Java class is invoked in a derived class.
There was a fair amount of churn in the terminology during the first years of object oriented programming as various people worked in the area and published papers and books and developed Object Oriented Languages. It was all quite new and exciting and people were trying to decide the proper vocabulary to use so they were trying out various words and phrases to express Object Oriented concepts.
And with a number of Object Oriented Programming languages that have been developed and gained popularity, a community developed around the language with a particular vocabulary. So older and more experienced programmers who were into object oriented early on may call things a bit different.
Parent and child is also used in describing other kinds of Is-A or Has-A relationships. For instance Parent window and Child window is also used for windowing systems in which a window, the Child, is contained within another window, the Parent. So the Parent window Has-A Child window.

I'd say it's the same.
You might want to differentiate between a direct and indirect parent or super class, but I guess the two terms are not clear enough on this, either. So if this is what you are trying to express, better be explicit.
Also, many programming languages have the "super" keyword used to refer to the (single) direct parent class. But even there, if you call a "super" method and the direct parent does not implement it, it also bubbles up.

They are different terms to address the same OOP concept: inheritance. If class ChildClass extends ParentClass you can say:
ChildClass parent class is ParentClass
ParentClass is the super-class of ChildClass
Inheritance levels have nothing to do there, it doesn't matter if a Super-Class itself extends another class.

They are essentially the same. Depending on the language, the terminology changes. Parent may mean the immediate parent, while Super class may mean any of the ancestor classes. In addition, in java, there is the super() method, which calls the parent's constructor.

In Ruby language we have both the concepts meaning different things.
ParentClass -> ChildClass -> this is used for namespacing
and
SuperClass -> SubClass -> this is used for inheritance
Examples below:
ParentClass -> ChildClass:
class A
def self.f1
puts "A -> #{self.name}.f1 called"
end
# B is childclass of A
class B
def self.f2
puts "B -> #{self.name}.f2 called"
end
end
end
# C is subclass of A
class C < A
def self.f3
puts "C -> #{self.name}.f3 called"
B.f2
end
end
See the output below:
C.f1
A -> C.f1 called
C.f3
C -> C.f3 called
B -> A::B.f2 called

Related

is it true that "Metaclass class" is just Metaclass?

I came across with the following statements:
(Metaclass class) new. "Uses the new of Behavior but throws error because Metaclass class is singleton"
Metaclass new. "Uses the new of Behavior"
I thought that Metaclass class is Metaclass then why the answers are different?
I can't seem to figure out how the method lookup works. Which hierarchy tree I need to follow? Where can I find an almost full tree that has the basic classes?
The class/metaclass relationship is among the most complex topics in Smalltalk, yet is part of the elegance of how everything fits together in a consistent manner.
Method lookup starts in a MethodDictionary held by the class of the object (the class describes the object) and proceeds up the inheritance chain.
Generally you should not be creating new instances of Metaclass, but should let the IDE/tools make it for you as a side-effect of creating a new class (sending #'subclass:...' to an existing superclass).
You can find a tree of basic classes in your Smalltalk image. Details depend on the dialect, and Squeak should have a "Class Hierarchy Browser" that allows you to look at things.
Following is a picture that helps me visualize the relationships.
There is some magic in the message #new, whose understanding requires some effort. What should call our attention is this:
How it is possible for a class to understand #new given that #new is implemented in Behavior, which is not a superclass of our class?
For example, Object new creates a brand new instance of Object even though Object is not a subclass of the root implementor of #new (e.g., Behavior).
To better understand this, note that Object new is not a message sent to an instance of Object but to the class Object. Therefore the lookup will start at the class of Object which is a Metaclass, namely Object class.
It looks like the lookup mechanism through metaclasses would follow a special pathway: It starts at the alluded metaclass, say Object class. If it doesn't find the selector, it goes up in the inheritance hierarchy all the way up to ProtoObject class if needed. But, it doesn't stop here. It jumps to the abstract class Class to continue the lookup. From there it goes up following the hierarchy again. This happens with all messages sent to a class, not just with #new. In the case of Object new, it will find the implementor in Behavior.
There is something interesting observe:
When the lookup reaches Class it is no longer a class-side search, it is now an instance-side one.
A question remains:
How is it possible for the lookup to jump from ProtoObject class to Class?
Well, there is actually no jump at all. What happens is this:
ProtoObject superclass == nil.
but
ProtoObject class superclass == Class
and since the lookup sends the #superclass message to follow the inheritance chain, it will naturally transition from ProtoObject class to Class without having to do anything special.
The particular detail here is that for all classes, except ProtoObject we have
AnyClass class superclass == AnyClass superclass class "<- algebraic commutativity"
However, for ProtoObject this is not the case, the superclass of ProtoObject is nil but the superclass of ProtoObject class is Class.
Note
This also the only case where a Metaclass has a superclass which is not a Metaclass. That is precisely the exception which resolves the modeling circularity.

Are protocols really the replacement of superclass?

I watched the Protocol-oriented programming video from WWDC15. After I saw this video, I got confused. Can anyone give me a relevant example illustrating this idea?
And more over protocol extension is the really replacement of operators overloading.
In dynamically typed languages (Ruby, Python, Javascript, etc) there is the concept of "duck typing", which essentially says it doesn't matter what the actual type of an object is, as long as it responds to certain methods. Rather than checking instance_of?, you can check responds_to? which is more relevant when you're using the check to determine if you can call a method anyway.
Protocols are simply a formal declaration of a duck type. Since you asked for an example (code is Ruby, which is dynamically typed — if you're unfamiliar with Ruby, just treat it as pseudocode and imagine everything typed as id and return values are void):
Imagine we're building a program to model transportation. We might have a few different modes of transportation:
class Bicycle
def goto(x, y)
# Implementation details
end
end
class Car
def goto(x, y)
# Implementation details
end
end
class Boat
def goto(x, y)
# Implementation details
end
end
class Jetpack
def goto(x, y)
# Implementation details
end
end
It would probably not make sense for all these classes to be subclasses of a Vehicle parent class, since a Jetpack would have very different properties and implementation details from a Bicycle. But notice that all these classes respond to the goto(x, y) method. It would be easy to create another class (like Helicopter, for example) that also responds to this method.
Now imagine we're using one of these classes:
class Person
def travel(vehicle, destination)
vehicle.goto(destination.x, destination.y)
end
end
This code would work regardless of if vehicle is a Bicycle, Boat, or some other class defined in the future, because this code is calling a protocol method rather than a type method.
A. The basic problem
Think of this situation:
You have instances of class A that interacts with other instances. As have to know the API of the class the other instances are of. There are two ways to accomplish that:
The other instances are of the (likely virtual) base class B and A knows the class B (via import or whatever). In such a case A can rely on Bs capabilities.
The other instances implements the protocol B and A knows the protocol B (via import or whatever). In such a case A can rely on Bs capabilities, too.
The disadvantage of solution 1 is that A dictates the (base) class of the other instances. This can lead to a problems: First of all, the base class B cannot fit. Additionally maybe B should act as "Helper" for many classes, not only A. This would lead to multiple inheritance. No, no, no, nobody wants that.
Multi-protocol implementation is no problem.
B. Subclassing vs. delegating + protocol as pattern for specialization
In many cases you will find a base class A that should be specialized for some reasons, i. e. data access and providing. In a class based programming language you will find a (virtual) base class A and subclass it. Beside the problems discussed under A), you will find some others:
Subclassing is white boxing: Subclasses know more than other classes.
A base class contains many methods. What is the set of methods that are ought to be overwritten?
With protocols (and delegating) you can change that: Whenever a base class wants to be specialized, it puts the method into a protocol and "calls" an instance that implements the protocol (sends a message to the implementor of that protocol), when it needs specialized information. Another class can (optionally) implement this protocol and act as specialator.
This is called delegating, implemented using protocols and replaces subclassing.
C. More abstract
You can see that in a more abstract way:
Protocols declares a set of methods, an API.
Classes declares a set of methods, an API, and implement them.
So the difference between both is that classes are implementors.
So there is a rule of thumb: If you care about implementing something, use a subclass, because you can inherit much code from the base class. If you care about declaring an API, chose a protocol (and implement that in a class, not a subclass).

Is "composition over inheritance" simply mean "If parent class is never be used except in child class, it should be composition"?

I read some posts about "composition over inheritance","where to use composition/inheritance" , "Is-a relationship..." or "Liskov substitution principle" for some time, but I am not sure if I get the right idea about "composition over inheritance".
Alternatively, In my experience, "composition over inheritance" seems just mean "If parent class is never be used except by child class, it should be composition", for example:
public class Parent{
}
public class Child1 extends Parent{
}
public class Child2 extends Parent{
}
If class "Parent" is never appeared at my code other than in Child1 and Child2, then Child1 and Child2 should not be the child class of Parent.
Is that right?
Composition-over-inheritance means that instead of structuring your class hierarchy using a parent class and extending child classes, you should do something like this:
class Foo {
protected bar;
protected baz;
public function Foo(Bar _bar, Baz _baz) {
bar = _bar;
baz = _baz;
}
}
In other words, instead of inheriting a bunch of functionality from a base parent class, you get this same functionality from independent objects instead which you preferably dependency inject into your class.
Why? Because it provides more flexibility. In the case of Foo extends Bar, Bar provides some base functionality which is useful for a bunch of inheriting classes. Now, who says this functionality isn't also useful for a bunch of other, unrelated classes? Should all your classes inherit from Bar? Should all common functionality be stuffed into Bar because all classes inherit from it? Please no, that just leads to fat, monolithic, unmaintainable base classes.
Instead, implement any collection of useful common methods in their own independent class. Group only functionality which is closely related, separate into different classes as makes sense. Then inject those objects into other objects to compose a new object which can use all that shared functionality without inheriting monolithic base classes or defining an abstract strict class hierarchy.
You should only inherit a class if they share the same "business logic" hierarchy. E.g., Cat extends Pet extends Animal makes perfectly logical sense. Cat extends BaseConnectionManager less so.
If you're using class hierarchies for type hinting, interfaces can serve this purpose much better and more flexibly too.
I generally find that when re-use is the goal, inheritance is attractive. However, in this situation, composition always turns out to be the better solution. For me, inheritance is best used for its polymorphism.
Inheritance is a specific tool. Composition is a general tool. Both are useful, but in different contexts.
Inheritance is useful when you want to ensure that all objects of type Foo are also, in every respect, objects of type Bar. This means more than just implementing the same methods. It means Foo objects must perfectly emulate Bar objects in every outwardly-visible respect. If they do not, then the Liskov Substitution Principle is violated, and inheritance is a poor choice for the situation at hand.
Composition is much more general. It is used to divide responsibilities among multiple classes while still allowing for properly abstracted and defined interactions between them. It does not require the specific, Liskov-like relationship I just described.
"Composition over inheritance" is just the observation that composition is a more general technique than inheritance. Because of this, composition should be the tool we reach for first in most situations, rather than inheritance. This does not mean that every use of inheritance is wrong, or even that inheritance is inherently bad. It's a way of thinking, not a coding standard.

How do you model this in a class diagram?

Say I have an interface Interface and a concrete class ConcreteClass that implements Interface. Now consider a third class MyClass. If instances of MyClass hold a reference to ConcreteClass:
Interface ref = new ConcreteClass();
then should I associate MyClass with Interface or ConcreteClass in UML class diagram?
Thanks
That depends on what the public interface of MyClass defines.
If the public interface makes an Interface available, then you should link to that on the diagram. This would be the usual approach as the Interface is the general type and specifies the contract. Unless you have a reason to limit to ConcreteClass, don't.
If the public interface makes a ConcreteClass available, then you should link to that on the diagram.
The fact that at runtime a variable of type Interface actually holds an instance of ConcreteClass is beside the point. The diagram represents the relationships.
Solely with the Interface. The point is that you want the behavior of the interface. Whatever the implementation is of that interface is for the picture of no importance. MyClass has a relation with the interface, not with the implementation of the interface.
This principle is called Design By Interface. In the answer given by nakosspy is it his first picture. But it would even be better to leave the implementation of ConcreteClass out of the picture. The implementation is of no importance at that conceptual level. If there is a variable pointing to an interface, then is it obvious to the educated reader that there should be a concrete implementation as well.
If you would make a reference to the ConcreteClass then would you have to change the diagram everytime you change the implementation of the interface. That is not what you want. It is bad coding practice and bad uml practice.
It is good coding practice to separate the declaration of the relationship between MyClass and the Interface and the practical implementation of the Interface. By example:
Interface ref = new ConcreteClass();
should never happen in the class MyClass.
You should have something like this instead:
class MyClass
Interface ref;
setRef(){
ref = InterfaceImplementation();
}
}
This way can you change the implementation of Interface without changing one line of code in MyClass. Altough this might look much ado when you write one class, think of it when you are managing hundreds of classes.
So: it depends.
It's equally legal to associate MyClass with ConcreteClass or Interface. You won't find the answer to your question in the UML spec. Why? Because the answer lies in your problem domain, not the modelling language.
Consider two contrived examples to illustrate the point.
Example 1: Association between Classes
Substitute:
ICanBark for Interface
Dog for ConcreteClass
Trainer for MyClass
Let's assume the association we want to capture is Trains, i.e.
Each Trainer trains many Dogs
Each Dog is trained by at most one Trainer
In this case the association exists because of the 'Dogginess', not the 'Barkiness'. So it properly exists between the two classes.
Example 2: Association between Class and Interface
Substitute:
ILogger for Interface
FileLogger for ConcreteClass
Application for MyClass
In this case the relationship is about the 'Logginess', not the 'Fileness'. Application shouldn't care how the interface is implemented; it just wants a way to log messages. So the Association exists between the Class and the Interface
Summary
As is nearly always the case with Associations, the key to solving the problem lies in the problem domain itself - not the modelling language.
hth.
There are 2 ways to present the ref variable of MyClass: You can present it as attribute or as association. Then there are two alternative notations for the Interface interface: Square with the interface stereotype or circle. This makes 2*2=4 alternatives.
Show ref as association and use square interface notation.
Here you can't show the initial value that ref takes. That's because you can't show default values in associations.
Show ref as association but use the circle notation for the Interface.
As it was with the previous alternative, again here you can't show the initial value.
Show ref as attribute and use square interface notation.
Here you can show the default value, because you can do that for attributes. The relationship between MyClass and Interface is presented as a dependency. The same happens for the dependency between MyClass and ConcreteClass.
Note that this dependency (MyClass depends on ConcreteClass) can be presented also in the alternatives 1 and 2, you can add a dependency arrow (dashed) pointing from MyClass to ConcreteClass.
Show ref as attribute and use circle interface notation.
Again here you can show the default value.
If we count also the alternatives derived from presenting or not the dependencies, then there are at least 6 ways to present the same thing. Now the question is which to chose.
It depends on what do you want to visualize with the diagram and for whom the diagram is intended. In this case if the initialization of ref is the message, then you should use an alternative that presents it. If it's less important, then you might prefer a diagram that shows ref as association.
In a real problem you have more elements, so it makes much more alternatives. It's always up to you to decide what to present and how.
EDIT: Some references to help you understand the notation of interface implementation.
According to wikipedia:
A realization is a relationship between classes, interfaces,
components, and packages that connects a client element with a
supplier element. A realization relationship between classes and
interfaces and between components and interfaces shows that the class
realizes the operations offered by the interface.
You can find some quick reference examples and a lot of information at uml-diagrams.org.
This excellent answer Explanation of the UML arrows will help you with more examples.
Here you can also find some more info on realization.
You can define reference to concrete class as:
Attribute typed as Interface (or ConcreteClass) defined in MyClass, or
Association between MyClass and Interface (or ConcreteClass).
no more options are avialable

OOP Difference between a derived class and an inherited class?

From an OOP point of view is there any difference between a derived class and an inherited class? Or is it simply terminology?
When using inheritance, the inherited class is called the base class, and the inheriting class is called the
derived class.
The term derived class is preferred C++ parlance for a class that inherits from another class, which in C++ parlance is called a base class. So in C++ the terms you ask about are identical.
Neil's answer confused me a bit, and so I checked some public sources.
Consider a Base Class and a Sub Class (SubClass extends BaseClass in Java terminology), than
the Sub Class derives Base Class (Sub Class is a derived class of Base Class) and
the Sub Class inherits from Base Class (Base Class is a/the inherited class of Sub Class)
So in my opinion both terms define the same relationship between to classes but from different perspectives.
Inheritance terminology by Bertran Meyer (Object-Oriented Software Construction, p.464):
Basic conventions and terminology
The following terms will be useful in addition to “heir” and “parent”.
A descendant of a class C is any class that inherits directly or indirectly from
C, including C itself. (Formally: either C or, recursively, a descendant of an
heir of C.)
An ancestor of C is a class A such that C is a descendant of A.
In the literature you will also encounter the terms “subclass” and “superclass”, but
we will stay away from them because they are ambiguous; sometimes “subclass” means
heir (immediate descendant), sometimes it is used in the more general sense of proper
descendant, and it is not always clear which. In addition, we will see that the “subset”
connotation of this word is not always justified.
maybe interesting, if you override a method, in Delphi you write:
inherited; // so "inherited" is the base class
instead of
base.BaseImplementation(); // C#