I am just reading Dart language specification and exploring a new interesting language. As Dart language specification says: Dart has implicit interfaces. Which means every class is an interface too. So, If I want to implement some behavior of another class, implements clause is the only I need.
Also, Dart supports mixins. So that we can take implementation of methods from another class using with keyword.
So, given that if an abstract class A defines method a() like :
abstract class A {
void a();
}
and another two concrete class B defines method a() but does not implements class A like:
class B {
void a() {
print("I am class B");
}
}
and class C implements class A with Mixin B like :
class C extends Object with B implements A {
...
}
Here, I have few questions about it. If a class implements the interface and also use mixin that has method implementation with same method name; doesn't it would make cycling inheritance possible?
What will be the behaviour of class C? Does it need to implement a() or it will be implicitly implemented by mixin B?
I am just learning Dart and concepts like mixins are very unfamiliar to me. Can anyone help me understanding by answering my questions?
Mixins are a kind of limited multiple inheritance. With C with B, C inherits an implementation of void a(). Adding implements A doesn't need anything more to be done, because C already fulfills the contract it claims to fulfill by implements A, because of B.
Your link is to the Language Tour, not the specification, but the tour is definitely what you should be reading to start with.
Your example is just fine. class C extends Object with B { ... } basically adds the members of B to Object to create C. If C then satisfies the interface A it can declare support for that interface ( implements A ).
Related
Assume we have a parent class A and a child class B inheriting from it. A has the method m() which is overwritten by B. Let's also assume we have a third class C, which has call-dependency to class A. Is it possible for C to call the overwriting method m() from class B in UML2?
This clearly depends on the language you are using. Personally I don't know of any language that allows that. Instead you would likely (generally) have an operation in B that offers the pure functionality of B's superclass' method:
And the call sequence could be like
Yes, in UML2 and in most OO programming languages, like C++, C# and Java, it is possible that C executes behavior that calls method m of B.
In terms of UML, if you have this class diagram:
then this is a valid sequence diagram:
Method callM is implemented such that it calls p.m(). When you call callM, you may pass an actual parameter of type B, because it's compatible with formal parameter p of type A. The effect of p.m() will then be that the overridden method m in B will be called. This is also known as polymorphism.
class A {
public m();
}
class B extends A {
public m();
}
class C {
public callM ( p : A ) {
p.m(); // calls either A::m or B::m, depending on actual type of p
}
}
b = new B;
c = new C;
c.callM(b); // let c call method m of class B
For more examples, click here for online study material
I have seen few similar questions, but none had explained why delegation is limited to interfaces?
Most of the time in practice we have something that has actually no interface at all, it is a class that implements nothing but provides some functionality or implements an abstract class.
Is there any fundamental limitation that forces this to be limited to interfaces or can we expect kotlin to have unrestricted delegation in the future?
This is especially useful if we want to extend functionality of a class using composition not inheritance.
class A {}
class B(val a: A) : A by a {}
When you delegate an interface, the class does still implement the interface. So for consistency, if you can delegate a class, it should work the same way. I.e.
class A(x: Int) {
fun foo() = x
}
class B(val a: A) : A by a {}
needs to compile to
class B(val a: A) : A {
override fun foo() = a.foo()
}
except this doesn't work:
foo isn't open and can't be overridden.
you need to call a constructor of A. class B(val a: A) : A(a.x) won't help either: x is not a member of A.
What about equals and hashCode: are they delegated? Either decision would lead to weird consequences.
This is a general Object Oriented Programming question:
Suppose I am given a base class B:
class B {
// member functions
}
and suppose I am told to create an instance of B through the following factory method:
B createB(/* arguments */) {
b = ...
return b;
}
Now, the problem is that I need to derive from B but how am I going to initialize it as createB() does?:
class D : B {
D() {
/* need to use createB() to
initialize the base because
no equivalent constructor
exists. */
}
}
Using factory methods is in many aspects much better than just directly calling constructors. Once you've chosen using factory methods, you should stick to this approach for all the derived class - otherwise you violate the basic reason for why the factory methods have been introduced: separate the object creation from object usage.
Hence, instead of solving the issue of accessing the factory method for class B from the constructor of class D, think about creating a factory method also for the class D. Or even better: create a common factory method B createB(arguments) which decides itself what type it creates and returns.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Creating an abstract class in Objective C
In Java I like to use abstract classes to make sure that a bunch of classes has the same basic behavior, e.g.:
public abstract class A
{
// this method is seen from outside and will be called by the user
final public void doSomething()
{
// ... here do some logic which is obligatory, e.g. clean up something so that
// the inheriting classes did not have to bother with it
reallyDoIt();
}
// here the actual work is done
protected abstract void reallyDoIt();
}
Now that if class B inherits from class A, it only has to implement reallyDoIt().
How to make this in Objective C? Is it at all possible? Is it feasible in Objective C? I mean the whole paradigm seems to be different in Objective C e.g. from what I understand there is no way to forbid overriding a method (like in Java with 'final')?
Thanks!
There is no actual constraint on not overriding a method in objective c. You can use a protocol as Dan Lister suggested in his answer but this is only good to enforce your conforming class to implement a certain behavior declared in that protocol.
A solution for an abstract class in objective c could be :
interface MyClass {
}
- (id) init;
- (id) init {
[NSException raise:#"Invoked abstract method" format:#"Invoked abstract method"];
return nil;
}
This way you can prevent methods in your abstract class to be invoked (but only at run-time unlike languages like java which can detect this when on compile-time).
You'll want to use something called Protocols I think.
Is there a case where a companion object (singleton) for a class is needed? Why would I want to create a class, say Foo and also create a companion object for it?
The companion object basically provides a place where one can put "static-like" methods. Furthermore, a companion object, or companion module, has full access to the class members, including private ones.
Companion objects are great for encapsulating things like factory methods. Instead of having to have, for example, Foo and FooFactory everywhere, you can have a class with a companion object take on the factory responsibilities.
Companion objects are useful for storing state and methods that are common to all instances of a class but they do not use static methods or fields. They use regular virtual methods which can be overridden through inheritance. Scala truly has nothing static. There are lots of ways you can use this but here's a simple example.
abstract class AnimalCounter
{
var animals = 0
def name: String
def count()
{
animals += 1
println("%d %ss created so far".format(animals, name))
}
}
abstract class Animal
{
def companion: AnimalCounter
companion.count()
}
object Dog extends AnimalCounter
{
val name = "dog"
}
class Dog extends Animal
{
def companion = Dog
}
object Cat extends AnimalCounter
{
val name = "cat"
}
class Cat extends Animal
{
def companion = Cat
}
Which produces this output:
scala> new Dog
1 dogs created so far
scala> new Cat
1 cats created so far
scala> new Dog
2 dogs created so far
scala> new Cat
2 cats created so far
...and it's a good place to store static factory methods (not that DP) for accompanied classes. If you name those overloaded factory methods apply(/.../) you will be able to create/initialize you class
without 'new' (not really that important)
with different possible sets of parameters (compare to what Bloch writes in Effective Java about telescoping constructor)
with the ability to to decide which derived class you want to create instead of the abstract (accompanied) one
Example code:
abstract class AbstractClass;
class RealThing(s: String) extends AbstractClass;
class AlternativeThing(i: Int) extends AbstractClass;
object AbstractClass {
def apply(s: String) = {
new RealThing(s)
}
def apply(i: Int) = {
new AlternativeThing(i)
}
}
// somewhere else you can
val vs = AbstractClass("asdf") // gives you the RealThing wrapped over string
val vi = AbstractClass(123) // gives you AlternativeThing wrapped over int
I wouldn't call the object/base class AbstractXxxxx because it doesn't looks bad: like creating something abstract. Give those names a real meaning.
Consider using immutable, method less, case classes and seal the abstract base class.
In addition to the things Saem said in his reply, the Scala compiler also looks for implicit conversions of types in the corresponding companion objects (of either the source or the target), so the conversions don't need to be imported.
About the reason for singleton objects in general Programming in Scala says:
As mentioned in Chapter 1, one way in which Scala is more object-oriented than Java is that classes in Scala cannot have static members. Instead, Scala has singleton objects (p. 65).
I always see companion objects as a bridge to write both functional and object oriented code in Scala. Many times we just need pure functions which take some input and provide a processing result. Putting those relevant functions in the companion object makes it easy to look up and use, for myself as well as some one building on top of my code.
Moreover, it is a language provided feature to write the singleton pattern without doing anything. This is especially useful when you need a singleton to encapsulate a delegator for the life of JVM. For example, writing a simple HTTP client library in Scala where you can encapsulate an underlying Java implementation based delegator and let consumers of your API live in pure world.
If you define class and object in same file with same name, they known as companion class and object. Scala don't have static as JAVA keyword, You can take as replacement of static with companion class and object in Scala.
For more detail information please check article
class and object keyword in scala programming
At first, it provides a clear separation of static vs non static methods methods.Also provide a simple way to create singleton class.
It also can inherit methods from other classes and/or traits, which cannot be done with Java static methods.and can be passed as a parameter.