VB.NET make method of object accessible only for certain other object - vb.net

I have declared 2 classes: A and B. They are connected as an object tree: Object A holds a "list of B" as private member variable.
EDIT: I am declaring 3 classes: A, B and C. A holds list of B and B holds list of C.
All my object data is stored in a database (1 table per object).
Each object has a method "delete", which will delete his own database record ("suicide").
B.delete should only be called from A which will then also remove the item from his own "list of B".
I want, that method B.delete can only be invoked internally or by a member of object A.
EDIT: and C.delete can only be invoked internally or by a member of object B.
However other methods in B and C must remain public.
Is this possible?
What would be the declaration / approach / architecture?

Related

object composition in PDDL

I'm very new to PDDL and stumbling into something basic.
The object model is something along the line of:
Object A has multiple numeric properties: Object B is a collection of Object A,
as part of the pre-condition in an action where the parameter passed is Object B, properties of all Object A's (that are contained in Object B) need to satisfy certain criteria.
Using functions, I can define numeric properties of Object A, but I don't know how to capture "Object B is a collection of Object A"?
I'm not sure if it adheres to your problem specification, but couldn't you just define a predicate is_part_of(?x - ObjectA ?y - ObjectB) to define this property?
Then in the precondition you can use a forall quantifier on all objectA. In the forall body state that when the predicate is true, the objects have to satisfy the criteria. Note that PDDL has the when keyword that makes this easy. Otherwise you could encode this as just a simple or by encoding the alternative.

How to mimic simple inheritance with base and child class constructors in Lua (Tutorial)

How to mimic simple inheritance with parent and child class constructors in Lua?
I will provide and accept and answer and would greatly appreciate if you commented on it or edited interesting information into it.
This is a guide for mimicking basic parent/child class inheritance in Lua.
I assume that basic features and syntax of Lua are known to the reader. The following statements are especially important:
There are no classes or objects in Lua, just tables.
A table can have a metatable.
If the metatable mt of a table t contains the __index metamethod (thus mt.__index), access to a non-existent key in t is attempted to be resolved via what's assigned to mt.__index.
If t calls a function t.foo() like this t:foo() then t itself is passed to foo() as the first argument called self. Inside the function, t itself is accessible as self.
Base class
Code
Base = {}
function Base:new(name)
Base.__index = Base
local obj = {}
setmetatable(obj, Base)
obj.name = name
return obj
end
function Base:sayName()
print(self.name..": My name is "..self.name..".")
end
Because of what the function Base:new(name) does, Base can now be seen as a new class, with Base:new(name) being its constructor. Remember that Base really is a table that sits somewhere in memory, not some abstract "class blue print". It contains a function Base:sayName(). This is what we could call a method with respect to OOP lingo.
But how does Base:new(name) let Base act like a class?
Explanation
Base.__index = Base
The Base table gets an __index metamethod, namely itself. Whenever Base is used as a metatable, searches to a non-existent index will be redirected to... Base itself. (Wait for it.) The line could also be written as self.__index = self, because Base calls :new(name) and thus self is Base therein. I prefer the first version, because it clearly shows what's happening. Also, Base.__index = Base could go outside of Base:new(name), however, I prefer having all the "set up" happen inside one scope (the "constructor") for the sake of clarity.
local obj = {}
setmetatable(obj, Base)
obj is created as a new empty table. It will become what we think of as an object of the "class" Base. The Base is now the metatable of obj. Since Base has an __index, access to non-existent keys in obj well be redirected to what is assigned to Base.__index. And since Base.__index is Base itself, access to non-existent keys in obj will be redirected to Base (where it would find Base:sayName(), for instance)!
obj.name = name
return obj
The obj (!) gets a new entry, a member, to which the constructor parameter is assigned. The obj is then returned and is what we would interpret as an object of class Base.
Demonstration
b = Base:new("Mr. Base")
b:sayName()
This prints "Mr. Base: My name is Mr. Base." as expected. b finds sayName() via the metatable-__index mechanism as described above, because it doesn't have such a key. sayName() lives inside Base (the "class table") and name inside b (the "object table").
Child class
Code
Child = {}
function Child:new(name, age) -- our child class takes a second argument
Child.__index = Child
setmetatable(Child, {__index = Base}) -- this is different!
local obj = Base:new(name, age) -- this is different!
setmetatable(obj, Child)
obj.age = age
return obj
end
function Child:sayAge()
print(self.name..": I am "..tonumber(self.age).." years old.")
end
The code is almost exactly the same as for the base class! Adding a second parameter in the Child:new(name, age) (i.e. the constructor) is not especially noteworthy. Base could also have had more than one parameter. However, the second and third line inside Child:new(name, age) were added and that is what causes Child to "inherit" from Base.
Note that Base may contain Base.__index, which makes it useful when used as a metatable, but that it has no metatable itself.
Explanation
setmetatable(Child, {__index = Base})
In this line, we assign a metatable to the Child class table. This metatable contains an __index metamethod, which is set to the Base class table. Thus, the Child class table will try to resolve access to non-existent keys via the Base class table. Thus, the Child class table has access to all of its own and all of Base's methods!
local obj = Base:new(name, age)
setmetatable(obj, Child)
In the first line, a new Base object table is created. At this point, its __index metamethod points to the Base class table. However, right in line two, its metatable is assigned to the Child class table. The reason why obj does not lose access to Base class methods lies in the fact that we redirected non-successful key accesses in Child to Base (by giving Child the proper metatable) just before! Since obj was created as a Base object table, it contains all of its members. Additionally, it also contains the members of a Child object table (once they are added in the Child:new(name, age) "constructor". It finds the methods of the Child class table via its own metamethod. And it finds the methods in the Base class table via the metamethod in the Child class table.
Note: With "Base object table" I mean the table that is returned by Base:new(name). With "Base class table" I mean the actual Base table. Remember, there are no classes/objects in Lua! The Base class table and the Base object table together mimic what we think of as OOP behavior. The same goes for Child, of course.
Also, scoping the assignment of Child's metatable inside Child:new(name, age) allows us to call Base's "constructor" and pass the name argument to it!
Demonstration
c = Child:new("Mrs. Child", 42)
c:sayName()
c:sayAge()
This prints "Mrs. Child: My name is Mrs. Child." and "Mrs. Child: I am 42 years old." as expected.
Conclusion
The sections above described how to implement OOP behavior in Lua. It is important to understand that
Base methods live inside the Base class table
Base members live inside the Base object table returned by Base:new()
Child methods live inside the Child class table
Child members live inside the Child object table returned by Child:new()
Referencing the correct tables is accomplished by the table's metatables.
All class tables assign themselves to their __index key. When used as metatables, they refer to themselves (i.e. where the class methods live). There is only one class table per "class".
Base classes don't have a metatable. They are used as metatables.
Child class tables also have a metatable, namely {__index = Base} (which redirects calls to the Base class table, i.e. where the Base class methods live).
All object tables assign their corresponding class tables as metatables. Since the class tables have set their __index metamethod, calls to the object tables can be redirected to the class tables where the class methods live. If it is a child class table (which means it also has a metatable), the redirection can happen even further. There can be arbitrarily many object tables.
Use the image above to follow along: What happens if a Child object table c tries to access a Base method, e.g. c:sayName()? Well: Has c a sayName() key? No. Does it have a metatable? Yes: Child (the Child class table). Does Child have an __index metamethod? Yes. Where does it point? To Child itself. Does Child have a sayName() key? No. Does Child have a metatable? Yes. Does it have an __index metamethod? Yes. Where does it point? To the Base class table. Does it have a sayName() key? Yes! :-)
Note
I am no Lua expert! I have only done some scripting in Lua so far, but over the last days I tried to wrap my mind around this. I found a lot of different, sometimes confusing solutions and finally arrived at this, which I would call the most simple but transparent solution. If you find any errors or caveats do not hesitate to comment!

Accessing the base part of a derived object

Lets say I am given an object O on some method.
This object O is derived from a base Object BaseClass and as such has a part whose type is BaseClass.
How can I access this part when I am in this method, which means super wont work because I am not in the context of the object.
Thanks!
Let me re-phrase your question to make sure I understand it. You have a class O containing a method (say "test"). In that method, you want to access an instance variable belonging to the superclass BaseClass.
If this is correct, then you can already access that instance variable directly. You just need to provide the name of the variable. Your subclass has access to all of the instance variables visible to the superclass.
You should consider creating get and set methods for the variable and accessing the variable by calling those methods from the subclass, but it's optional.
Let me provide another answer, which could be useful for cases where the question refers to behavior (methods) rather than shape (instance variables.)
Assume you have two classes C and D and an instance c of C. Now assume C inherits from C' and you would like to invoke a method m defined in C' that has been overridden in C. The expression c m will activate the implementation in C rather than the one in C' because c class == C, not C'. As you said, there is no "remote" version of super that you could use from D.
If what you want is to activate the method in C', then you should move the source code of m in C' to another method, say m0, and redefine m in C' so that it just delegates to m0 (^self m0). Keep the method m in C unchanged and then call from D using m0 (c m0) instead of m (c m).
Note that the other way around will not work: if you define m0 in C' as ^self m, the expression c m0 will activate the version of m found in C, not C'.
You could also define m0 in C as ^super m and that way c m0 will activate C'>>m. However, the usage of super with a different selector is not considered a good practice, and you should chose not to do that.

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

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

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.