When can a reference's type differ from the type of its object? - oop

Yesterday I was asked a question in an interview:
Suppose class A is a base class, and class B is derived class.
Is it possible to create object of:
class B = new class A?
class A = new class B?
If yes, then what happen?

Objects of type B are guaranteed to also be objects of type A. This type of relationship is called "Is-a," or inheritance, and in OOP it's a standard way of getting polymorphism. For example, if objects of type A have a method foo(), objects of type B must also provide it, but its behavior is allowed to differ.
The reverse is not necessarily true: an object of type A (the base class) won't always be an object of type B (the derived class). Even if it is, this can't be guaranteed at compile-time, so what happens for your first line is that the code will fail to compile.
What the second line does depends on the language, but generally
Using a reference with the base type will restrict you to only accessing only members which the base type is guaranteed to have.
In Java, if member names are "hidden" (A.x exists and so does B.x, but they have different values), when you try to access the member you will get the value which corresponds to the type of the reference rather than the type of the object.
The code in your second example is standard practice when you are more interested in an API than its implementation, and want to make your code as generic as possible. For instance, often in Java one writes things like List<Integer> list = new ArrayList<Integer>(). If you decide to use a linked list implementation later, you will not have to change any code which uses list.
Take a look at this related question: What does Base b2 = new Child(); signify?

Normally, automatic conversions are allowed down the hierarchy, but not up. That is, you can automatically convert a derived class to its base class, but not the reverse. So only your second example is possible. class A = new class B should be ok since the derived class B can be converted to the base class A. But class B = new class A will not work automatically, but may be implemented by supplying an explicit conversion (overloading the constructor).

A is super class and B is a SubClass/Derived Class
the Statement
class A = new class B is always possible and it is called Upcasting because you are going Up in terms of more specific to more General
Example:
Fruit class is a Base Class and Apple Class is Derived
we can that Apple is more specific and must possess all the quality of an Fruit
so you can always do UPcasting where as
DownCasting is not always possible because Apple a=new Fruit();
A fruit can be a Apple or may it is not

Related

When is a class a data class?

I know what classes are about, but for better understanding I need a use case. Recently I discovered the construct of data classes. I get the idea behind normal classes, but I cannot imagine a real use case for data classes.
When should I use a data class and when I use a "normal" class? For all I know, all classes keep data.
Can you provide a good example that distinguishes data classes from non-data classes?
A data class is used to store data. It's lighter than a normal class, and can be compared to an array with key/value (dictionary, hash, etc.), but represented as an object with fixed attributes. In kotlin, according to the documentation, that adds those attributes to the class:
equals()/hashCode() pair
toString() of the form "User(name=John, age=42)"
componentN() functions corresponding to the properties in their order of declaration.
copy() function
Also it has a different behavior during class inheritence :
If there are explicit implementations of equals(), hashCode(), or toString() in the data class body or final implementations in a
superclass, then these functions are not generated, and the existing
implementations are used.
If a supertype has componentN() functions that are open and return compatible types, the corresponding functions are generated for the
data class and override those of the supertype. If the functions of
the supertype cannot be overridden due to incompatible signatures or
due to their being final, an error is reported.
Providing explicit implementations for the componentN() and copy() functions is not allowed.
So in kotlin, if you want to describe an object (a data) then you may use a dataclass, but if you're creating a complex application and your class needs to have special behavior in the constructor, with inheritence or abstraction, then you should use a normal class.
I do not know Kotlin, but in Python, a dataclass can be seen as a structured dict. When you want to use a dict to store an object which has always the same attributes, then you should not put it in a dict but use a Dataclass.
The advantage with a normal class is that you don't need to declare the __init__ method, as it is "automatic" (inherited).
Example :
This is a normal class
class Apple:
def __init__(size:int, color:str, sweet:bool=True):
self.size = size
self.color = color
self.sweet = sweet
Same class as a dataclass
from dataclasses import dataclass
#dataclass
class Apple:
size: int
color: str
sweet: bool = True
Then the advantage compared to a dict is that you are sure of what attribute it has. Also it can contains methods.
The advantage over to a normal class is that it is simpler to declare and make the code lighter. We can see that the attributes keywords (e.g size) are repeated 3 times in a normal class, but appear only once in a dataclass.
The advantage of normal class also is that you can personalize the __init__ method, (in a dataclass also, but then you lose it's main advantage I think) example:
# You need only 2 variable to initialize your class
class Apple:
def __init__(size:int, color:str):
self.size = size
self.color = color
# But you get much more info from those two.
self.sweet = True if color == 'red' else False
self.weight = self.__compute_weight()
self.price = self.weight * PRICE_PER_GRAM
def __compute_weight(self):
# ...
return (self.size**2)*10 # That's a random example
Abstractly, a data class is a pure, inert information record that doesn’t require any special handling when copied or passed around, and it represents nothing more than what is contained in its fields; it has no identity of its own. A typical example is a point in 3D space:
data class Point3D(
val x: Double,
val y: Double,
val z: Double
)
As long as the values are valid, an instance of a data class is entirely interchangeable with its fields, and it can be put apart or rematerialized at will. Often there is even little use for encapsulation: users of the data class can just access the instance’s fields directly. The Kotlin language provides a number of convenience features when data classes are declared as such in your code, which are described in the documentation. Those are useful when for example building more complex data structures employing data classes: you can for example have a hashmap assign values to particular points in space, and then be able to look up the value using a newly-constructed Point3D.
val map = HashMap<Point3D, String>()
map.set(Point3D(3, 4, 5), "point of interest")
println(map.get(Point3D(3, 4, 5))) // prints "point of interest"
For an example of a class that is not a data class, take FileReader. Underneath, this class probably keeps some kind of file handle in a private field, which you can assume to be an integer (as it actually is on at least some platforms). But you cannot expect to store this integer in a database, have another process read that same integer from the database, reconstruct a FileReader from it and expect it to work. Passing file handles between processes requires more ceremony than that, if it is even possible on a given platform. That property makes FileReader not a data class. Many examples of non-data classes will be of this kind: any class whose instances represent transient, local resources like a network connection, a position within a file or a running process, cannot be a data class. Likewise, any class where different instances should not be considered equal even if they contain the same information is not a data class either.
From the comments, it sounds like your question is really about why non-data classes exist in Kotlin and why you would ever choose not to make a data class. Here are some reasons.
Data classes are a lot more restrictive than a regular class:
They have to have a primary constructor, and every parameter of the primary constructor has to be a property.
They cannot have an empty primary constructor.
They cannot be open so they cannot be subclassed.
Here are other reasons:
Sometimes you don't want a class to have a copy function. If a class holds onto some heavy state that is expensive to copy, maybe it shouldn't advertise that it should be copied by presenting a copy function.
Sometimes you want to use an instance of a class in a Set or as Map keys without two different instances being considered as equivalent just because their properties have the same values.
The features of data classes are useful specifically for simple data holders, so the drawbacks are often something you want to avoid.

Why parent class is not able to access child class member

If we go according to below code
class A;
int a = 10;
endclass
class B extends A;
int b = 20;
endclass
program test;
A a1;
B b1;
initial begin
b1 = new();
a1 = b1; //child class object is assigned to parent class handle
$display("Value of variable b is %x", a1.b);
end
endprogram
Then the above code results into error that "Could not find member 'b' in class 'A'"
Now my observation is that when extended class object is assigned to base class handle then simulator will check the type of handle and check whether variable is present in that class or not. As variable b is not defined in base class then it will result into error.
So I want to confirm whether my above observation is correct or incorrect?
I would welcome if anyone wants to add something to my observation, in case it's correct.
Thanks
You are correct, and it is the intended behavior in OOP languages I know (I don't especially know the one you are using, but your example is simple enough). Being able to use a variable declared by a child class would result in a violation of the object oriented principle of polymorphism (or subtyping).
I will answer you in Java, because I'm sure of the syntax in this language for the example i want to give. Imagine two variables with the same declared type :
public A buildA () {
return new B();
}
public static void main () {
A a1 = new A();
A b1 = buildA();
}
The polymorphism principle is that a1 and b1 should implement the same interface and be used indifferently. If I was allowed to access a variable's member b, since the compiler couldn't guess which is base and which is child, then it would allow the program to crash at runtime every time I access a concrete A, removing the safety net types are supposed to provide.
I would not use the terms parent and child class here. It implies you have two separate class objects.
What you describe is two different class types where one type is derived/extended from a base type. Then you declare two class variables: a1 and b1. These variables may hold a handle to class object of the same type, or a handle to an object of any type extended the type of the variable. However, the compiler will not let you reference any variable or member that has not been defined by type of the class variable regardless of the type of the object the class variable currently hold a handle to.
OOP gives you the ability to interact with a class variable with the possibility of it having a handle to much more complex object without you knowing what extensions have been made to that object. But you have to assume that the object could be the same type as the class variable. The compiler enforces this as well. If you want to interact with the extended class variables, you need to use an extended class variable type.

Type of user defined class objects - Python

I am not very experienced with classes or OOP,
and I'm confused with some of the results I'm getting.
I am trying to use type() on a class I have created.
class TestClass:
pass
my_class = TestClass()
print type(my_class)
The above code returns
<type: 'instance'>
Based on my understanding my_class should be initialized as a TestClass object.. right? Why isn't the output TestClass. Also, if possible, what would I need to change to get this result?
From the documentation:
Classes and instances come in two flavors: old-style (or classic) and
new-style.
Up to Python 2.1, old-style classes were the only flavour available to
the user. The concept of (old-style) class is unrelated to the concept
of type: if x is an instance of an old-style class, then x.__class__
designates the class of x, but type(x) is always <type 'instance'>.
This reflects the fact that all old-style instances, independently of
their class, are implemented with a single built-in type, called
instance.
By not inheriting from object, you create an old-style class, so type(my_class) behaves like it does.
Inherit from object and your problems will go away:
class TestClass(object):
pass
In Python 3, all classes are new-style classes, which is nice.
If you want TestClass to be an object, you have to specify it like so
class TestClass(object):
pass

More specific Type from base shared constructor

How do I get using reflection the most generic type from a shared constructor in the base class :
Public Class Foo()
Shared Sub New()
'Here we have code to get the type!
MethodBase.GetCurrentMethod().DeclaringType
End
End Class
Public Class Bar()
Inherits Foo
End Class
I expect the result to be Bar type and not the Foo. Is it possible?
First, it seems you want to find the most derived type (or the most specific type), not the most generic type -- which would mean rather the opposite (either, that generics are involved, or that the most general type is being sought).
While it may be possible to do this using reflection, your need for it might indicate that you have your class design wrong, or less than optimal.
First, constructors aren't virtual methods, so inside a constructor (IIRC), the Me object reference is of the type that contains this constructor.
What you could do is reflect over all of an assembly's types and find all those that are derived from Foo. You would then have to build a inheritance graph of these types and assign a number to each saying how far it is derived from Foo (number of inheritance levels). You could then check the Me object reference against all of the types you've identified (see if Me can be cast to each of them), and from that subset, choose the one type with the largest number of inheritance levels.
I hope that from this, you'll see that it's probably not worth the effort. It would be more interesting, and probably more helpful, to re-think why you need to do this, and if possible, find a way to avoid it.

What is the difference between an Instance and an Object?

What is the difference between an Instance and an Object?
Is there a difference or not?
The Instance and Object are from Object Oriented Programming.
For some programming languages like Java, C++, and Smalltalk, it is important to describe and understand code. In other languages that used in Structured Programming, this concept doesn't exist.
This is a view from Structural Programming. There's no real significant difference that should consume too much of your time. There might be some fancy language that some people might take up a lot of spaces to write about, but at the end of the day, as far as a coder, developer, programmer, architect, is concerned, an instance of a class and an object mean the same thing and can often be used interchangeably. I have never met anyone in my career that would be picky and spend a half-hour trying to point out the differences because there's really none. Time can be better spent on other development efforts.
UPDATE With regards to Swift, this is what Apple who invented Swift prefers :
An instance of a class is traditionally known as an object. However,
Swift classes and structures are much closer in functionality than in
other languages, and much of this chapter describes functionality that
can apply to instances of either a class or a structure type. Because
of this, the more general term instance is used.
Excellent question.
I'll explain it in the simplest way possible:
Say you have 5 apples in your basket. Each of those apples is an object of type Apple, which has some characteristics (i.e. big, round, grows on trees).
In programming terms, you can have a class called Apple, which has variables size:big, shape:round, habitat:grows on trees. To have 5 apples in your basket, you need to instantiate 5 apples. Apple apple1, Apple apple2, Apple apple3 etc....
Alternatively: Objects are the definitions of something, instances are the physical things.
Does this make sense?
Instance: instance means just creating a reference(copy).
object: means when memory location is associated with the object (is a run-time entity of the class) by using the new operator.
In simple words, Instance refers to the copy of the object at a particular time whereas object refers to the memory address of the class.
Object:
It is a generice term basically it is a Software bundle that has state(variables) and behaviour(methods)
Class:
A blue print(template) for an object
instance-it's a unique object thing for example you create a object two times what does that mean is yo have created two instances
Let me give an example
Class student()
{
private string firstName;
public student(string fname)
{
firstName=fname;
}
Public string GetFirstName()
{
return firstName;
}
}
Object example:
Student s1=new student("Martin");
Student s2=new student("Kumar");
The s1,s2 are having object of class Student
Instance:
s1 and s2 are instances of object student
the two are unique.
it can be called as reference also.
basically the s1 and s2 are variables that are assigned an object
Objects and instances are mostly same; but there is a very small difference.
If Car is a class, 3 Cars are 3 different objects. All of these objects are instances. So these 3 cars are objects from instances of the Car class.
But the word "instance" can mean "structure instance" also. But object is only for classes.
All of the objects are instances.
Not all of the instances must be objects. Instances may be "structure instances" or "objects".
I hope this makes the difference clear to you.
Let's say you're building some chairs.
The diagram that shows how to build a chair and put it together corresponds to a software class.
Let's say you build five chairs according to the pattern in that diagram. Likewise, you could construct five software objects according to the pattern in a class.
Each chair has a unique number burned into the bottom of the seat to identify each specific chair. Chair 3 is one instance of a chair pattern. Likewise, memory location 3 can contain one instance of a software pattern.
So, an instance (chair 3) is a single unique, specific manifestation of a chair pattern.
Quick and Simple Answer
Class : a specification, blueprint for an object...
Object : physical presence of the class in memory...
Instance : a unique copy of the object (same structure, different data)...
An object is a construct, something static that has certain features and traits, such as properties and methods, it can be anything (a string, a usercontrol, etc)
An instance is a unique copy of that object that you can use and do things with.
Imagine a product like a computer.
THE xw6400 workstation is an object
YOUR xw6400 workstation, (or YOUR WIFE's xw6400 workstation) is an instance of the xw6400 workstation object
Java is an object-oriented programming language (OOP). This means, that everything in Java, except of the primitive types is an object.
Now, Java objects are similar to real-world objects. For example we can create a car object in Java, which will have properties like current speed and color; and behavior like: accelerate and park.
That's Object.
Instance, on the other side, is a uniquely initialized copy of that object that looks like Car car = new Car().
Check it out to learn more about Java classes and object
Once you instantiate a class (using new), that instantiated thing becomes an object. An object is something that can adhere to encapsulation, polymorphism, abstraction principles of object oriented programming and the real thing a program interacts with to consume the instance members defined in class. Object contains instance members (non-static members).
Thus instance of a class is an object. The word ‘instance’ is used when you are referring to the origin from where it born, it's more clearer if you say ‘instance of a class’ compared to ‘object of a class’ (although the latter can be used to).
Can also read the 'Inner classes' section of this java document on nested classes - https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
I can't believe, except for one guy no one has used the code to explain this, let me give it a shot too!
// Design Class
class HumanClass {
var name:String
init(name:String) {
self.name = name
}
}
var humanClassObject1 = HumanClass(name: "Rehan")
Now the left side i.e: "humanClassObject1" is the object and the right side i.e: HumanClass(name: "Rehan") is the instance of this object.
var humanClassObject2 = HumanClass(name: "Ahmad") // again object on left and it's instance on the right.
So basically, instance contains the specific values for that object and objects contains the memory location (at run-time).
Remember the famous statement "object reference not set to an instance of an object", this means that non-initialised objects don't have any instance.
In some programming languages like swift the compiler will not allow you to even design a class that don't have any way to initialise all it's members (variable eg: name, age e.t.c), but in some language you are allowed to do this:
// Design Class
class HumanClass {
var name:String // See we don't have any way to initialise name property.
}
And the error will only be shown at run time when you try to do something like this:
var myClass = HumanClass()
print(myClass.name) // will give, object reference not set to an instance of the object.
This error indicates that, the specific values (for variables\property) is the "INSTANCE" as i tried to explain this above!
And the object i.e: "myClass" contains the memory location (at run-time).
This answer may be seen as trite, but worrying about the differences between an instance and object is already trite city.
I think its best depicted in javascript:
let obj= {"poo":1}
// "obj" is an object
verses
Class Trash {
constructor(){this.poo = 1;}
}
let i = new Trash();
// "i" is an instance
When a variable is declared of a custom type (class), only a reference is created, which is called an object. At this stage, no memory is allocated to this object. It acts just as a pointer (to the location where the object will be stored in future). This process is called 'Declaration'.
Employee e; // e is an object
On the other hand, when a variable of custom type is declared using the new operator, which allocates memory in heap to this object and returns the reference to the allocated memory. This object which is now termed as instance. This process is called 'Instantiation'.
Employee e = new Employee(); // e is an instance
However, in some languages such as Java, an object is equivalent to an instance, as evident from the line written in Oracle's documentation on Java:
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.
An instance is a specific representation of an object. An object is a generic thing while an instance is a single object that has been created in memory. Usually an instance will have values assigned to it's properties that differentiates it from other instances of the type of object.
If we see the Definition of Object and Instance object -
Memory allocated for the member of class at run time is called object or object is the instance of Class.
Let us see the Definition of instance -
Memory allocated For Any at run time is called as instance variable.
Now understand the meaning of any run time memory allocation happen in C also through Malloc, Calloc, Realloc such:
struct p
{
}
p *t1
t1=(p) malloc(sizeof(p))
So here also we are allocating run time memory allocation but here we call as instance so t1 is instance here we can not say t1 as object so Every object is the instance of Class but every Instance is not Object.
Object - An instance of a class that has its own state and access to all of the behaviour defined by its class.
Instance - Reference to an memory area for that particular class.
Class : A class is a blue print.
Object : It is the copy of the class.
Instance : Its a variable which is used to hold memory address of the object.
A very basic analytical example
Class House --> Blueprint of the house. But you can't live in the blue print. You need a physical House which is the instance of the class to live in. i.e., actual address of the object is instance. Instances represent objects.
There are 3 things you need to understand : Class , Object and Instance.
Class : Class is the blueprint code from which you will create an Object(s)
Object : When memory is allocated to the data entity (created from blueprint class) , that data entity or reference to it is called Object
Instance : When data is filled in an Object , it becomes an instance of that Object. It can also be called a state of that Object.
Example : In context with C# (objects are reference type here)
Lets say we have a class like this (This is your blueprint code)
public class Animal
{
//some fields and methods
}
We create an object like this
Animal a = new Animal();
Animal b = a;
Animal c = a;
Animal d = b;
So here is the question : How many objects and instances are here ?
Answer : There is only 1 object but 4 instances.
Why ?
In first line (Animal a = new Animal();),we created an Object from class Animal with new Operator. That Object is somewhere on your RAM. And the reference to that Object is in "a".
We have 1 object and 1 instance at this time.
Now in next line, we assign b with a. Here Object is not copied but the reference of object from "a" is stored in "b" too. Thus , we have 2 instances , "a and b".
This goes on and we only copy reference of same object located at some memory.
Finally , we have 4 instances "a,b,c,d" of a single object that was created with new Operator.
(Read how reference type works in C# for more. I hope you understand my language)
each object said to be an instance of its class but each instance of the class has its own value for each attributes
intances shares the attribute name and operation with their intances of class but an object contains an implicit reference to his on class
I can't believe this could be hard to be explain but it actually easier than all the answers I read. It just simple like this.
Firstly, you need understand the definition:
Instance is a **unique copy-product of an Object.
**unique - have different characteristic but share the same class compare to object
Object is a name that been used to keep the Class information (i.e
method)
Let say, there is an toy_1 as an object.
There is also toy_2 as an object ----> which ALSO an INSTANCE to toy_1.
At the same time, toy_1 also an INSTANCE to toy_2. (remember again INSTANCE is a COPY-PRODUCT)
That is why most of the answer I found said it is INTERCHANGABLE. Thank you.
I think if we consider other approaches than OOP (mainly by assuming the term Class hasn't always been used, as it's the case for many C projects, which still applied the concept of Objects), following definitions would make the most sense:
A Class defines an interface that objects adhere to.
An Object is an aggregate of different fields. (It doesn't have to "physically" exist, but it can).
All Objects of the same Class can be used in the same way, defined by the Class.
An Instance is a unique realization of an Object.
As many OOP languages use static typing, the Object description is usually part of the Class already. As such, when talking about an Object in C/C++, what usually is meant is the Instance of an Object.
In languages that do not have static typing (such as JavaScript), Objects can have different fields, while still sharing the same Class.
Regarding the difference between an object and an instance, I do not think there is any consensus.
It looks to me like people change it pretty much interchangeably, in papers, blog posts, books or conversations.
As for me, the way I see it is, an object is a generic and alive entity in the memory, specified by the language it is used in. Just like the Object class in Java. We do not much care its type, or anything else associated with it, whether it is managed by a container or not.
An instance is an object but associated with a type, as in this method accepts Foo instances, or you can not put Animal instances in an instance of
a List of Vehicles.
objects for example have locks associated with them, not instances, whereas instances have methods. objects are garbage collected, not instances.
But as I said, this is only how I see it, and I do not think there is any organisation we can refer to for a standard definition between them and everyone will pretty much have their slightly different understanding / definitions (of course within limits).
An object is a generic thing, for example, take a linear function in maths
ax+b is an object, While 3x+2 is an instance of that object
Object<<< Instance
General<<< Specific
There is nothing more to this
An object can be a class, say you have a class called basketball.
but you want to have multiple basketballs so in your code you create more than 1 basketball
say basketball1 and basketball2.
Then you run your application.
You now have 2 instances of the object basketball.
Object refers to class and instance refers to an object.In other words instance is a copy of an object with particular values in it.