On iOS, why can UIGestureRecognizer be instantiated, if it is an abstract class? - iphone

The following code using UIGestureRecognizer:
UIGestureRecognizer *gestureRecog = [[UIGestureRecognizer alloc]
initWithTarget:self
action:#selector(handletap:)];
[self.view addGestureRecognizer:gestureRecog];
can actually compile and run. I thought abstract class cannot be instantiated?

Abstract classes are not a language feature in Objective-C (unlike Java, for example), so it isn't something the compiler could enforce.
When a class is marked as abstract in the documentation, it is just a hint how it is intended to be used, but neither the runtime, nor the compiler will actually prevent you from instantiating it directly.
The section on abstract classes in the Objective-C Programming Language Guide actually states that NSView is an example of an abstract class that you may sometimes use without subclassing, so the concept as such is not as strict as in other languages/frameworks.

Thanks for omz's answer. This is the related excerpt from Apple's documentation:
Abstract Classes
Some classes are designed only or primarily so that other classes can
inherit from them. These abstract classes group methods and instance
variables that can be used by a number of subclasses into a common
definition. The abstract class is typically incomplete by itself, but
contains useful code that reduces the implementation burden of its
subclasses. (Because abstract classes must have subclasses to be
useful, they’re sometimes also called abstract superclasses.)
Unlike some other languages, Objective-C does not have syntax to mark
classes as abstract, nor does it prevent you from creating an instance
of an abstract class.
The NSObject class is the canonical example of an abstract class in
Cocoa. You never use instances of the NSObject class in an
application—it wouldn’t be good for anything; it would be a generic
object with the ability to do nothing in particular.
The NSView class, on the other hand, provides an example of an
abstract class, instances of which you might occasionally use
directly.
Abstract classes often contain code that helps define the structure of
an application. When you create subclasses of these classes, instances
of your new classes fit effortlessly into the application structure
and work automatically with other objects.

Related

Abstract classes and abstract methods

Hey I have being looking a lot and watching a lot of videos about inheritance.
There is just this concept of abstract classes which means that it cant be implemented.
I get that you cant use a abstract class on a gameobject but what is the force of using a abstract class?
Also can abstract method only be implemented in a abstract class, and why cant you implement the method in a abstract class but only override it?
I also read something about a abstract method taking a component<T> and I havent found out what the purpase of that was hope some of you clever minds can help a confused programmer :D
Abstract classes are used to model a shared "master class" which will never be used itself but derived classes of it will use that data/functions.
For example say your inheritance is
Animal
Bird Mammal Reptile
In your game, you will only ever use a Bird/Mammal/Reptile since those are concrete models of animals, But they all will share at least some common amount of code. Health, Hunger, and may provide some abstract functions such as Move() which will be implemented on a per subclass level.
From an engineering standpoint, this let's you do fancy things such as create an array/vector of type Animal which can contain birds, mammals, and reptiles.
So say we have a vector of type Animal with 1 of each subclass.
We can then do
foreach (Animal a in animals)
a.Move(100)
Birds/Mammals/Reptiles all move differently, but because we have that abstract function with no implementation at the base level, our code can guarantee that at some point in the inheritance tree it is implemented.
Other popular examples are an abstract class of Item and the abstract function item.Use(); Item could be a Potion, a Scroll, an apple (class Food). It doesn't matter because they all share that same base level interface.
I think reading Microsoft's article on Abstract Classes and Methods would be extremely helpful. You utilize abstract classes by providing base functionality to a class and inheriting from it.
You're also confusing some wording with implement and override: you implement an abstract method by overriding it.
Component<T> means that the class Component with the type parameter as something you define. This is defined in C# as Generics. You utilize these with base Unity3D classes like Component<GameObject> or GetComponent<GameObject>.

When should I use a regular class in Scala?

It seems to me that I can make just about anything using object, trait, abstract class and in rare occasions, case class. Most of this is in the form object extends trait. So, I'm wondering, when should I, if ever, use a plain, standard class?
This is not a right place to ask this question
Looks like you are new Scala
Class is a specification for something(some entity) you want to model . It contains behavior and state
There is only one way to declare so called regular class using keyword class
Both trait and abstract class are used for inheritance.
trait is used for inheritance (generally to put common behavior in there). trait is akin to interface in Java. multiple inheritance possible with traits but not abstract class.
A class can extends one class or abstract class but can mixin any number of traits. Traits can have behavior and state.
case class is a nothing but a class but compiler produces some boilerplate code for us to make things easy and look good.
object is used when you want to declare some class but you want to have single instance of the class in the JVM (remember singleton pattern).
If an object performs stateful computations on its members i.e. its members are declared with vars;
Or, even if its member are only declared with vals but those vals store mutable data structures which can be edited in place, then it should be an ordinary (mutable) class akin to a Java mutable object.
The idiomatic way of using Case classes in Scala is as immutable types i.e. all the constructor arguments are vals. We could use vars but then we lose the advantages of case classes like equality comparisons will break over time.
Some advise from Programming in Scala by Odersky et al on deciding between using traits, abstract classes and concrete classes:
If the behavior will not be reused, then make it a concrete class. It is not reusable behavior after all.
If it might be reused in multiple, unrelated classes, make it a trait.
Only traits can be mixed into different parts of the class hierarchy.
If you want to inherit from it in Java code, use an abstract class.
Since traits with code do not have a close Java analog, it tends to be
awkward to inherit from a trait in a Java class. Inheriting from a
Scala class, meanwhile, is exactly like inheriting from a Java class.
As one exception, a Scala trait with only abstract members translates
directly to a Java interface, so you should feel free to define such
traits even if you expect Java code to inherit from it. See Chapter 29
for more information on working with Java and Scala together.
If you plan to distribute it in compiled form, and you expect outside
groups to write classes inheriting from it, you might lean towards
using an abstract class. The issue is that when a trait gains or loses
a member, any classes that inherit from it must be recompiled, even if
they have not changed. If outside clients will only call into the
behavior, instead of inheriting from it, then using a trait is fine.
If efficiency is very important, lean towards using a class. Most Java
runtimes make a virtual method invocation of a class member a faster
operation than an interface method invocation. Traits get compiled to
interfaces and therefore may pay a slight performance overhead.
However, you should make this choice only if you know that the trait
in question constitutes a performance bottleneck and have evidence
that using a class instead actually solves the problem.
If you still do not know, after considering the above, then start by
making it as a trait. You can always
change it later, and in general using a trait keeps more options open.

Concrete and abstract definitions in Scala.js facades

It's said in the documentation that
In native JS types, all concrete definitions must have = js.native as body. Any other body will be handled as if it were = js.native, and a warning will be emitted. (In Scala.js 1.0.0, this will become an error.)
And that's correct. However I found that I can omit body at all (thus making definition abstract) and there is no warning and generated js seems to be the same as with js.native body.
So my question is: what's the difference between abstract definitions and concrete definitions with js.native body?
The difference is that an abstract definition is abstract, and, well, a concrete definition (with = js.native) is concrete, from Scala's type system point of view.
But then what? From the use site of the class or trait, is doesn't make a difference. This is similar to normal Scala (or Java): when using a method, it doesn't matter whether it is abstract or not.
So the real difference is on the definition site. In theory, choosing abstract or concrete boils down to this criterium:
Does this method have an actual implementation in JavaScript code (not only a documented contract)? If yes, it should be concrete; if not, it should be abstract.
Practically and pragmatically, note that an abstract method can only appear in an abstract class or a trait, and must be implemented in a subclass/subtrait.
In terms of facade, in a native class, most methods should be concrete (if not all). That is because in JS, classes usually have concrete methods. In fact, abstract methods do not even exist in JS. The only reasonable case of defining an abstract method in a native class is if the "contract/documentation" of that class stipulates than a) it should be subclassed and b) subclasses should implement a particular method (not implemented in the superclass). This documented contract is as close as JS can get to abstract methods.
In JS traits, methods should usually be abstract (and the traits themselves be #ScalaJSDefined rather than #js.native). That is because traits/interfaces themselves do not even exist in JS. They only exist by their documented contract, which specifies what methods must/will be implemented by classes that satisfy this interface.
The only reasonable use case for concrete methods in (#js.native) JS traits is for DRYness. If several classes of a native API implement the same (large) set of methods, it can be reasonable to gather those methods in a native trait. In order not to have to repeat their definitions in all classes, they can be made concrete in the trait (if they were abstract, the classes would need to provided a concrete version to satisfy the contract). Note that such traits cannot be extended by non-native (#ScalaJSDefined) JS classes.
In the cases where you don't want to figure out the above "theoretical" criterium, use the following rule of thumb:
Is the method in a native JS class? If yes, it is almost certainly concrete.
Is it in a JS trait? If yes, it is almost certainly abstract (and the trait should be #ScalaJSDefined).

When to use an abstract class with no interface?

Whenever I create an abstract class I tend to create an interface to go along with it and have other code refer to the interface and not the abstract class. Usually when I don't create an interface to start with I regret it (such as having to override all implimented methods to stub the class for unit testing or later down the line new classes don't need any of the implimentation and override everything also finding themselves unable to extend any other class).
At first I tried to distinguish when to use an interface and when to use an abstract class by considering is-a vs able-to but I still would end up suffering later down the line for not making an interface to start with.
So the question is when is it a good idea to only have an abstract class and no interface at all?
When you wish to "give" some base class functionality to derived classes but when this functionality is not sufficient to instantiate a usable class, then go for abstract classes.
When you wish that some classes completely implement a set of methods (a public contract), then it is a convenient to define such contract with interfaces and enforce them onto classes by making them inherit this interface.
In short:
With abstract classes you give some common base functionality to derived classes. No further actions are necessary unless abstract class has some stubs (which have to be implemented down there).
With interfaces you require derived classes to implement a set of functions and you do not pass along any implementation.
So the question is when is it a good idea to only have an abstract class and no interface at all?
When you do not wish to enforce any public contract (a set of methods/properties defined by an interface).
Also when you do not plan to use certain coding techniques like casting object to an interface type (run-time polymorphism) or limit allowed input (some method argument will only accept object of types which implement certain interfaces).
Well, the main case it is useful to have only an abstract class without any interface is to mark a certain type. It is useful to be able to check if an object "is-a" something. These interface "mark" an objet to be of a certain type. Depending on the language you use, different design patterns apply ...
These sort of abstract classes exist in java. You can also use them in C++ with RTTI.
my2c

Is it good style to declare methods in .h when they're intended to be overwritten by subclass?

I have a class which is intended to be abstract. This means: When someone subclasses it, a few methods MUST be overwritten.
But on the other hand, those methods are not intended to be called manually from anywhere except inside the abstract class (the superclass of the subclass).
Must I declare these methods in .h anyways or can I just add comments in .h which say "you must overwrite -foo and -bar"? Or is there a better pattern to make abstract methods?
Related: Is there a way to create an abstract class in Objective C?
Objective-C doesn't actually have a way to declare a class as abstract. From Apple's Docs:
Abstract Classes
Some classes are designed only or
primarily so that other classes can
inherit from them. These abstract
classes group methods and instance
variables that can be used by a number
of different subclasses into a common
definition. The abstract class is
typically incomplete by itself, but
contains useful code that reduces the
implementation burden of its
subclasses. (Because abstract classes
must have subclasses to be useful,
they’re sometimes also called abstract
superclasses.)
Unlike some other languages,
Objective-C does not have syntax to
mark classes as abstract, nor does it
prevent you from creating an instance
of an abstract class.
The NSObject class is the canonical
example of an abstract class in Cocoa.
You never use instances of the
NSObject class in an application—it
wouldn’t be good for anything; it
would be a generic object with the
ability to do nothing in particular.
The NSView class, on the other hand,
provides an example of an abstract
class instances of which you might
occasionally use directly.
Abstract classes often contain code
that helps define the structure of an
application. When you create
subclasses of these classes, instances
of your new classes fit effortlessly
into the application structure and
work automatically with other objects.
So to answer your question, yes, you need to place the method signature in the header, and should implement the method in the base class such that it generates an error if called, like the related question's answer states.
You can also use a protocol to force classes to implement certain methods.
However you choose to implement the base class, clearly document in the header, as well as in your documentation, exactly what the class assumes and how to go about sub-classing it correctly.
Whenever possible write your code so that improper implementations fail to compile. If you cannot do that then you should try to generate a runtime error (at the very least in a debug build) if the subclass is not written correctly. Do not rely on comments because people will not read them.
You must declare your "protected" and "abstract" methods in a header file, but you can use separate categories to clearly indicate their purpose and intended use.
#interface MyBaseClass : NSObject {
}
- (void)foo;
#end
#interface MyBaseClass(ProtectedMethods)
- (void)bar;
#end
#interface MyBaseClass(AbstractMethods) // Subclasses must implement
- (void)internalBar;
#end
You can put everything in a single header, or you could put your protected and abstract declarations in a separate "protected" header, say MyClassProtected.h, meant to be included only by your subclass implementations. It depends on how badly you want "hide" your protected methods.
Your base class can log, assert, or throw when an abstract/pure-virtual method is called.
As other people have said, Objective-C does not support pure virtual classes.
You can enforce pure virtual behaviour at runtime though. The cleanest way to do this is by using the Objective-C runtime's _cmd and NSObject's -doesNotRecognizeSelector:
- (void)iMustBeImplementedInaSubclass;
{
[self doesNotRecognizeSelector:_cmd]; // Pure virtual
}
As ben says you are probably better served by using a protocol to get your API design right.