Class with no fields have constructor . is it possible ? - oop

We know that Constructors initialize the data fields of object . now if we don't have any fields in our class , There is nothing to be initialized by constructors.
What do constructors do in In such a class?

While it is the most obvious purpose of a constructor to initialize the data fields, it is by no means the only one.
The main purpose of the constructor is to create an object of the class. Without having an object, it is not possible to call any non-static methods of the class. You might say that non-static methods make no sense if the class has no data fields, but this is not true because derived classes might have data fields.
You should generally consider that the class could be part of a class hierarchy. (In Java, this is always the case because every class is derived from Object.) A constructor typically calls constructors of the base class.
Constructors can also have side effects. An example would be a message written to a log file. The created object could also be registered in some list when the constructor is called.

Related

Variable types in smalltalk

I need help understanding the usage and the difference of variables in Smalltalk.
What is the difference and the usage of each variable in the given code below?
Object subclass: #MyClass
instanceVariableNames: 'x'
classVariableNames: 'Yy'
poolDictionaries: ''
category: 'helpMe'
MyClass class
instanceVariableNames: 'zzz'
An instance variable (x) is a variable that is local to an instance. Neither the class nor any other instance can access that variable.
A class variable (Yy) is local to a class, all its instances, all subclasses and all subinstances (so the entire hierarchy). Any subclass or subinstance can see the value of that variable.
A class instance variable (zzz) is local to a class. Only the class that defines the variable has access to it, neither instances nor subclasses can see the variable (although subclasses inherit the declaration of the variable, their variable will have a different value).
Classes are also objects in Smalltalk. So you can think of a class instance variable the same way you would think about an instance variable: no other instance (instance of a class) can see the value. Thanks to #Amos M. Carpenter for pointing this out.
variables are identifiers. A variable holds a reference to some object.
instanceVariableNames: here x belongs to an instance of a class.
classVariableNames: here Yy have a copy of the variable shared with all instances of all classes, and it can be static a variable.
so x can have different values across different objects. But Yy can have only one value.
poolDictionaries: are created in smallTalk to provide access to variables shared among a group of classes
category 'helpme' is a collection of related classes, if you create your class without a category; the class gets created with a blank category.
subclass has its own instanceVariableNames(zzz), also has the inheritance property.
To avoid confusion among non-smalltalkers:
what you typed in was a message (to the Object class) to ask it to create a subclass of itself, named 'MyClass', with an instance variable (an instance-private slot) named 'x' and a class variable named 'Yy'. Followed by a message to that just created class to define a class instance variable (that is a slot in the class object - not in instances of it) named 'zzz'.
Global variables'Object' and 'MyClass' are "global variables". These are visible
everywhere and are technically bindings in a global Dictionary
(holding key-value pairs). In old implementations, there was only one
such dictionary; in more recent implementations, there are multiple, and they are called "namespaces". In your example, the class-definition message as sent to the Object class will create such a new binding for the 'MyClass' name.
Class variables'Yy' is a class variable; this also refers to a binding, but that binding is only visible inside the class and its subclasses, both to class methods and instance methods (see below). All referencing the same binding, thus subclasses will see the same value. They can be redefined in subclasses, but then again, all subclasses of the redefining subclass refer to the same binding.
Instance variablesthese are private slots of an object. 'x' is one in your example. The layout of an object and methods (operations) are inherited by subclasses, but of course, each individual instance has its own value. Instance variables are visible to instance methods (of course).
Class Instance Variablesbecause classes are themself objects (instances of a meta-class), these can have private slots as well. Technically, they are simply instance variables of the class object, and visible to class methods. As with instance variables, the layout and methods are inherited by subclasses, but each (class) has its own value. This is often misunderstood by C++/Java people, as they have no corresponding construct in their language (also be aware that class methods are inherited and can be redefined in Smalltalk, whereas static functions in other languages cannot)
Pool Variables (Shared Pools)are similar to class variables, in that they refer to bindings which are non-globally held by a class object. However, these are visible in a number of collaborating classes (similar to "friends" in another language). By naming a pool in the class definition message, its bindings become visible to the class and instance methods. Usually, these are used to define shared constants.
The other variable types (not present in your code example) are method-locals and block locals. These refer to slots in the current context, which is technically the stack-frame (continuation) of a method or a block (or an outer context, in case the block is actually a closure).
The 'category' is just an attribute of the class, not to be confused with the above variables. Think of it as a tag attached to it, to allow for a nicer organization in the browser. The details of where this attribute is stored is dialect specific: most use a separate (so-called "organization"), which is a dictionary. However, at least one dialect (ST/X) keeps it as a private slot of the class object (and there, it is really a variable in some sense).

Using properties vs passing parameter in a method

Which is better of the two
Creating properties and passing it within methods in class or passing objects as parameters to a method?
I have a datamodel object instance returned by a handler class, which i want to pass it to two different methods, so what is the best approach, assing it to a property in the class and then use it into these two methods, or pass the instance as a parameter to the method?
If an object is only needed temporarily by a class to extract data from for example, then pass it as an method argument.
You should take a step back from the code details and have a more abstract look: If the object has no direct purpose, or does not meaningfully belong with the class, then passing it as a method argument is fine. If the object could be seen as a part of the class (i.e. something the class needs all the time, or relies on a lot), then it might be an option to make it part of the class using a property.
Something else to consider is that setting a property, and then call a method that uses that property, separates the data from the operation. I mean, this obscures what the method does, and on what data it works. Of course this could be overcome by correct naming of those methods. Again look at things at a bit more abstract level to find the most meaningful way (i.e. what is closest to the purpose of the class and what the methods are actually doing) of structuring things.
In other cases these object may belong to underlying/other classes, which means that your current class is only passing them on. In those cases it's clear that you should literally pass them on with methods.

Inheritance Fundamentals

class Base
{
}
class Derive:Base
{
}
Base b=new Derive();
The above code works,but why we are able to create a Object of Derive Class and assigning it to Base Class reference.
Also,the object variable 'b' will be able to access all non private variable and methods of Class Base,even though it is referencing Derive Class.
What makes this possible,why the object variable 'b' which is referencing Derive Object is able to access the Base Class and not the Derive Class.
The theory allowing the above code to work is called the substitution principle: When Derived is a subtype of Base, this forms a "is-a" relationship. The substitution principle postulates that wherever an instance of Base is expected, it can be substituted by an instance of Derived.
The reason you cannot access the properties and methods of the Derive class later on is that (at least to a computer) there is no indication whatsoever that a variable of type Base contains an instance of type Derive which would allow access to these properties/methods. If you take another class DerivedToo : Base which has other methods than Derive you quickly see how the program could break if you assumed the Base variable to hold a Derive instance.
I think this is polymorhism question rather than inheritance.
One of the key features of derived classes is that a pointer to a derived class is type-compatible with a pointer to its base class. Using polymorphism you can take advantage of this feature.
Polymorhism allows you to invoke derived class methods through a base class reference during run-time. This is handy when you need to assign a group of objects to an array and then invoke each of their methods. They won't necessarily have to be the same object type. However, if they're related by inheritance, you can add them to the array as the inherited type.

What is the difference between an instance variable/method and a class variable/method in Objective-C?

I've seen many other questions on this same topic but they're not very clear to me, someone new to Objective-C.
I need a plain english explanation. 'Coder speak' is much too difficult for me to understand at this point in my learning.
An instance method or variable applies to that instance. A class method (classes in Objective-C don't have variables, though they can be simulated in various ways) applies to the whole class.
Consider the quintessential Dog class, which derives from the Mammal class (and so on up the tree of life.) A particular dog has a name and a collar and an owner--those are its properties. A particular dog may -bark or -chaseBall or -buryBoneInBackyard--those are its methods.
The Dog class, on the other hand, has different methods. The Dog class has a +globalPopulation and may instantiate itself with a +dogWithDNA: factory method. The Dog class will have an +isExtinct method indicating whether the species as a whole is extinct (it's not, of course.)
In short: class methods affect the entire class, while instance methods affect a particular instance of a class.
First, Objective-C does not have class variables. There are things that act sorts like class variables modally, but they aren't true class variables (see "static variables").
In Objective-C, every class is effectively an instance of a class. Thus, a class method is simply a method that applies to the class. They can be inherited and overridden.
Instance variables (ivars) and instance methods exist on each instance. There is one ivar per instance. Instance methods can not be called on classes.
Class variables^ and class methods do not not exist on instances, they exist on the class. That means that there will only ever be one class variable in the entire application regardless of how many instances are created. Class methods can be called without an instance*, so they kind of act like normal C functions. Because class methods are not attached to an instance, class methods can not access ivars.
^ Objective-C doesn't have class variables per se. "Class variables" are effectively static global variables in C.
* technically, a class is an instance, so class methods are actually instance methods in a sense.
A class is like a mold for something, that you can fill with plaster.
So a class level method is something that you can see and reach and use, without ever having to make a single object.
An instance is like pouring plaster into the mold and getting something out. You stamp out as many as you need; an instance variable then is a place on that object to hold something, and an instance method is something you can do with only that single object, not all of them.

Is Class an object, or is it a struct?

Is Class an object, or is it a struct?
Objective-C classes are considered as objects, with a few restrictions (see Objective-C Programming Language):
Class objects are thus full-fledged
objects that can be dynamically typed,
receive messages, and inherit methods
from other classes. They’re special
only in that they’re created by the
compiler, lack data structures
(instance variables) of their own
other than those built from the class
definition, and are the agents for
producing instances at runtime.
Behind the scene, a class definition contains various kinds of information, much of it about instances of the class:
The name of the class and its superclass
A template describing a set of instance variables
The declarations of method names and their return and argument types
The method implementations
Officially, it's implemented as a struct, but the Objective-C runtime let's you treat a Class as an object. Cocoa with Love has a great article on how classes and meta-classes work in Objective-C.
Class types are reference-types and struct types are value types. Instances of class or struct types are called objects.
Class is a type that can hold the pointer to a class object (similar to how id is a type that can hold the pointer to any object). Class is not the name of a class (similar to how id is not the name of a class). The class of a class object is the metaclass of that class (will not go into that here). Class objects are first-class objects; and you can do the same things with them as regular objects. Calling a method on a class object calls a class method on that class (or some ancestor class); you can also call the instance methods of the class's root class on a class object.