How to show usage of static methods UML Class Diagram - oop

How do i show the use of static methods in a UML class diagram?
class A{
public static void test(){
}
}
class B{
public void b(){
A.test();
}
}
How would a class diagram look like, which shows the relationship? UML 2.0 would be prepared, if there is a difference.

To show a static method you underline the name of the static method - have a look here for more detailed info.
As for navigating that relationship; class B is dependent on the existance of class A. We can say that class B has a "usage dependency" on class A
class B ----uses----> class A
Hope this helps.

#RobertMS is right.
Another alternative, is to use stereotypes:
..............................................................
....+----------------------------------------------------+....
....| StringUtilityClass |....
....+----------------------------------------------------+....
....| [+] void: lowerCase() <<non virtual>> |....
....| [+] void: upperCase() <<non virtual>> |....
....| [+] String: toString() <<override>> |....
....+----------------------------------------------------+....
....| [+] String: LowerCaseCopy(String Value) <<static>> |....
....| [+] String: UpperCaseCopy(String Value) <<static>> |....
....| [+] String: ReverseCopy(String Value) <<static>> |....
....+----------------------------------------------------+....
..............................................................
Note
Some programming languages best practices, especially those with C case-sensitive syntax, capitalize static functions, and leave in camel-lowercase the rest of functions.
Cheers.

To show static methods and attributes you underline them in a UML class diagram: see UML Distilled p.66 or section 7.3.19 (Feature) of the UML Superstructure specification:
Static features are underlined.
To show the relationship between classes B and A (where B only uses static methods in A), you use a dependency, not an association. Associations are always between instances of the classes at each end, as in section 7.3.3 (Association) of the UML Superstructure spec:
An association specifies a semantic relationship that can occur
between typed instances.
But class B is dependent on class A, as in section 7.3.12 of the spec:
A dependency is a relationship that signifies that a single or a set
of model elements requires other model elements for their
specification or implementation.
It is probably worth clarifying the nature of the dependency with a stereotype. You could use a use stereotype, but that's very general and actually encompasses standard associations between instances (though you obviously normally use associations to explicitly show them). As Fowler says in UML Distilled,
Many UML relationships imply a dependency. The navigable association
from Order to Customer [in one of his examples...] means that Order is
dependent on Customer.
There seems to be no standard on what stereotype to use. I've used usesStatically to be clear on the nature of the dependency; that is
B --usesStatically--> A
(If, alternatively, class B had an instance of A as a static field, I'd use something like B--containsStatically--> A if I'm representing B explicitly in the class diagram; otherwise just have an underlined static attribute of type A in B.)

Related

polymorphism vs inheritence as the pillars of oop

As stated here
https://standardofnorms.wordpress.com/2012/09/02/4-pillars-of-object-oriented-programming/
and as the correct answer in many job interviews - the general correct answer for the question:
"What are the 4 pillars of OOP?" is:
Abstraction
Encapsulation
Inheritance
Polymorphism
What I fail to understand is how inheritance not contained in polymorphism?
in other words, how can polymorphism be used without the use of inheritance?
The only way I know of using polymorphism is
class A{
virtual void foo(){cout<<"A";}
void bar(){cout<<"A";}
};
class B : public A{
virtual foo(){cout<<"B";}
};
A* ab = new B();
ab->foo();//prints B, using polymorphism
ab->bar();//prints A, using inheritance
A* a = new A();
a->foo();//prints A
a->bar();//prints A, obviously
As I see it, polymorphism brings with it inheritance.
Please explain why it is distinct - or why can't inheritance be discarded as a key pillar of its own. We could use polymorphism or not.
What I fail to understand is how inheritence not contained in
polymorphism?
in other words, how can polymorphism be used without the use of
inheritence?
There are 3 main types of polymorphism, and only one of them requires inheritance to work.
Ad-hoc polymorphism: This is more commonly known as function/method overloading, where multiple functions can share the same name but have different signatures. Whether or not the return type is part of the signature is language dependent.
Parametric polymorphism: in OOP, this is more commonly known as generics, where a function/method can work with multiple concrete types, and return multiple concrete types, providing compile time safety.
Subtype polymorphism: This is the one I think most people think of when they talk about polymorphism. As you know, this is when subtypes provide different implementation of their parent functions/methods.
You can read more about the different types of polymorphism from the wikipedia article here: https://en.wikipedia.org/wiki/Polymorphism_(computer_science)
As I understand the two concepts:
Inheritance
You could use inheritance without using polymorphisim. For example:
class Base {
public:
void foo();
};
class Derived : public Base {
};
int main() {
Derived d;
d.foo();
}
Here we use the common functionality of the base type in all derived types, but at no point do we do anything polymophic (we never look at the derived instance though its base interface).
Polymorphism
Polymorphism as a concept includes more than the standard inheritance based method seen most often. This is actually subtyping which is just one kind of Polymorphism.
Writing a template method is technically a form of polymophism, and function overloading another. As a concept you could argue that many other things are ways to achieve polymophism.
For example:
// This function must be given an object that has a method foo().
template <typename T> bar(T& t) {
t.foo();
}
This is polymorphic behavior without inheritance.
See: https://stackoverflow.com/a/10556406/1230538 for a really good explaination of this given by someone else.
Summary
99% you use inheritance to achieve polymorphism in most modern programming languages, but they are different concepts, and can exist/be used independently of each other.
Polymorphism without inheritance:
class A {
virtual void foo() { cout << "A"; }
};
class B {
virtual void foo() { cout << "B"; }
};
A* a = new A();
A* b = new B();
a->foo(); // prints A
b->foo(); // prints B
Both instances have the same method. So they are polymorphic. However, the method does different things because the objects are different after all.

emulate extendable algebraic types on scala

Traditional approach to algebraic types recommends something like it:
sealed trait CompositeType
final case class LeftBranch(left : String) extends CompositeType
final case class RightBranch(right : Int) extends CompoisteType
object Trivial extends CompositeType
The problem is that I can't extend CompositeType further to have more option (just like Double extends Float offering more accuracy and providing system for backward converting from Double to Float).
Scala gives you free to define own apply and unapply methods for building and matching instances of algebraic type.
Is there any project that tries to build framework for such types?
That may be usefull for actors metaphor. Currently actors receives untyped messages (as Any implies no type restrictions) matching known types and giving safe default for others. It breaks all type strict design of scala and restricting actors with more proper types would be really nice.
update:
Example clarifing my intentions:
sealed trait CompositeType1
final case class OtherBranch(x : Int, y : Int) extends CompositeType1
object Simple extends CompositeType1
trait ComplexChoice extends CompositionType with CompositionType1
I want to create CompositionType not as a root in type hierarchy but as one solid class. That may be extended further, mixing with other classes.
Let see some normal OOP usage:
trait ContractOne
trait ContractTwo
def method(arg : ContractOne with ContractTwo)
In this example function method need an argument that fit both contracts. What does mean contract for an algebraic type? Set of available constructors and matchers. What is natural view of extending an algebraic type? Extending set of constructors with some new values (just as Double extends Float with more precise floating point numbers)
CompositeType misses this conceptions evidiently. If I mix this two algebraic types I got set intersection instead of union. This is direct effect of chosen way for representing algebraic types as set of hierarchic subtypes. It gives more freedom to span choices outside initial types, but it lacks OOP features since inheritance is taken for element construction and may not be used for extending algebraic types itself.
Haskell has only one way for adding new choices to an algebraic type:
data CompositeType = LeftBranch String | RightBranch Int | Trivial
data CompositeType1 = OtherBranch Int Int | Simple
data ComplexChoice = CompositeType | CompositeType1
ComplexChoice is defined seamlessly in concept of haskell's data types. But handling it becomes complex, since I need reroute all methods as for composition. That's why composition is a solution in scala but troublesome and boilerplate one (if there is no compiler plugin that can generate code for composition pattern)
What I really need, is something like it:
ComplexChois condense CompositeType and CompositeType1
But object hierarchies may spawn only in one direction.
So there is need in some other way for defining algebraic types.
There is space for it since infinite expanding of original trait is not something that really needed and most such traits is used with sealed keyword. Therefore some other less powerfull mechanism than extending may be used to represent data types.
As you note, objects are the end of the line for derivation of subtypes. You could, in this case, create another level of intermediate abstract type from which to derive sub-types (singleton or otherwise) of Trivial:
sealed trait Trivial extends CompositeType
object Trivia extends Trivial { ... }
class Triviality extends Trivia(...) { ... } \
...

Inheritance, does the "is a" relationship always have to hold?

If class B inherits from class A, does class B always have to be a sub-type of A when used in inheritance?
I am thinking if it is possible to use inheritance to provide extra code to B, when B is not a subtype of A?
If type A inherits from B, that means two things:
Class `A` will be able to use public and protected static methods from class `B`, without having to specify the class name, and objects of class `A` will implicitly include all public and protected class members from `B` without having to respecify them.
Any code accepting objects of type `B` will, at at compile time, accept objects of type `A`, and objects of class `A` will be able to use class `B`'s public and protected instance methods on themselves.
Interfaces essentially embody concept #2 but not #1 (since interfaces have no static methods, and have no members that can be used implicitly without having to specify them). There is no built-in way to achieve #1 without #2; the only significant benefit of having #1 without #2 would be to save typing.
If:
class B extends A
Than B is by definition a subtype of A.
If you don't want that, you can use PHP's traits, which is basically interfaces with implementation.

What is the difference between inheritance and composition?

As title says, the meaning of both eludes me.
Inheritance expresses a is-a relationship, while composition expresses a has-a relationship between the two classes.
An example for composition is a polygon. It has a ordered sequence of Points. In C++ terms:
struct Polygon {
std::vector<Point> points;
};
While an logic_error is a exception:
struct logic_error : public exception {
};
Just google Inheritance vs Composition you'll get alot of results.
Using java as an example
public class Banana extends Fruit{ //<---Inheritance Banana is-a Fruit
private Peel bananaPeel; //<--Composition banana has a Peel
public Peel getPeel(){
return bananaPeel;
}
}
As pmr pointed out, inheritence is a is-a relationship, composition is a has-a relationship.
Composition is usually used for wrapping classes and to express relationships between classes that contain one another.
Inheritance is used for polymorphism, where you have a base class and you want to extend or change its functionality.
Inheritance means inheriting something from a parent.
For example, you may inherit your mother's eyes or inherit your father's build.
It means deriving properties, characteristics and behaviors from a parent class. So you can parent.walk(), parent.sleep(), parent.sleep() or whatever.
Containership or maybe composition is a bit hard to explain.
Or maybe a car has a brake. The car is composed of a brake. But the brake isn't inheriting from a brake..different concepts. I know very weird explanation..but that's how much I can do I guess.
Let's look at this code:
class Parent
{
public :
void sleep() ; void eat() ; void walk() ;
string eyeColor; int height ;
};
class Child: public Parent
{
}
So the Child class can inherit the functions and attributes of the Parent but of course it may have the eye color of the mother or father.. Even if the childs' attributes are different it can still do whatever the Parent can do.
Now composition is another thing. A Child can have a toy or a Parent can have a child. So I could do:
class Toy
{
string model ;
};
class Child
{
Toy transformersToy ;
};
So the Child has the transformers toy now.. but does Child inherit the transformersToy.model attribute? No, because it isn't inheriting.
inheritance is a relationship between classes, containership is relationship between instance of classes.
inheritance is the dynamic polymorphism, that these days change its functionality to a technic of a code reuse. but the composition is a technic for ensuring capability of implementation.
One main point I see is the ownership on the objects. Inheritance doesnt own/give any thing it just gives the characteristics of the base class. While Composition gives the owner ship to the created object.
In the first example polygon has a vector of points. So polygon owns/contains points in it.
While in inheritance you can have/use/extend the existing characteristics of the base class.

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.