Can an instance variable belong to multiple classes? - oop

I have been looking at classes in OOP and was curious to how this works.
For example, lets say I have a product. The product is a bike.
There could be a class for the product stock and a class for the products details e.g. colour etc.
I could use classes within each other for this such as a class called product and within it it contains both the stock and details for the product(bike)
Or could i have an instance called bike that is made from both
e.g.
Stock bike = new Stock();
details bike = new details();
or would the instance bike have to be renamed for them e.g.
Stock stockbike = new Stock();
details detailsbike = new details();
Hopefully that makes sense. Essentially I just wondered whether one instance keyword can belong to 2 classes or does the instance name in this case bike have to be changed so it can belong to more classes.
Thanks

Stock bike = new Stock(); details bike = new details();
Not quite sure what you're asking... but I think what you're asking is if you can have 2 variables with the same name and in the same scope. Generally, no. You didn't mention your language but let's assume Java.
public void test() {
String test = "123";
String test = "123"; // Error
Integer test = 123; // Also an error
Stock bike = new Stock();
Details bike = new Details(); // Error
}
One case where you COULD have the same name... although discouraged... is a local variable with the same name and type a variable of higher scope
public class Test {
private String myString;
...
public void test() {
String myString = "123"; // Warning and discouraged
}
}

I don't think there is an OOP rule that describes this.
In some language, you can have multiple inheritance, though. So you can have a class Bike which inherits from both Stock and Details. And after you've defined that class, you can just make a normal instance from it.
Reading material: Wikipedia on Multiple inheritance. Also describes languages that implement this, one way or another.

Related

How do you pass an ArrayList into the constructor?

import java.util.ArrayList;
public class Finance {
ArrayList<String> title = new ArrayList<String>();
ArrayList<Double> moneySpent = new ArrayList<Double>();
Scanner input = new Scanner(System.in);
public Finance(ArrayList<String> title, ArrayList<Double> moneySpent){
this.title = title;
this.moneySpent = moneySpent;
System.out.println(title);
System.out.println(moneySpent);
}
public static void main(String[] args){
Finance entertainment = new Finance(title.add("Movies"), moneySpent.add(1));
}
When I run the code this, I found 2 errors:
File: D:\Java Programs\Finance.java [line: 19] Error: Cannot make a
static reference to the non-static field title
File: D:\Java
Programs\Finance.java [line: 19] Error: Cannot make a static
reference to the non-static field moneySpent
Although your focus is in creating an instance Finance there are few concepts I'd like to invite you to explore.
To start and to answer your question, the Finance's contructor signature defines the contract for a Finance oject to become an instance.
It expects two arguments, each of which are of ArrayList type.
To create an instance of Finance you have to create two arrays, one made of Strings and the other made of Doubles, on this thread you have many ideas on how to initialise arrays.
An example could be,
new Finance(new ArrayList<>(List.of("Movies")), new ArrayList<>(List.of(1.0)));
Next, I'd like to drag your awareness on this expression in your code:
title.add("Movies")
title is what you want initialised inside your constructor and altough is not a bad idea to have it initialised as an empty ArrayList as you did, it's pointless to add an element to it and then pass it to your constructor for it to change the same instance object.
Next, I'd like to drag your awareness on the types you are using:
In my personal opinion I would use java's List interface when declaring variables, use a plural to name any collection of objects, and in your case, use ArrayList as the List interface implementing class. For example,
List<String> titles;
// and
List<Double> expenses;
Same on the constructor:
public Finance(List<String> titles, List<Double> expenses) {
//...init variables here
}
Note that I renamed moneySpent to expenses. I did this because a money spent on multiple moments it's more likely to be expenses and moneySpent would be the amount spent on a single moment.
Applying Single Resposibility I would refactor the creation of a Finance instance onto a separete (static, why static?) method.
public class Finance {
List<String> titles;
List<Double> expenses;
Scanner input = new Scanner(System.in);
public Finance(List<String> titles, List<Double> expenses) {
this.titles = titles;
this.expenses = expenses;
System.out.println(this.titles);
System.out.println(this.expenses);
}
public static void main(String[] args) {
Finance entertainment = createFinance();
}
private static Finance createFinance() {
return new Finance(
new ArrayList<>(List.of("Movies")),
new ArrayList<>(List.of(1.0)));
}
}
Lastly, Consider driving your implementation guided by tests. I can recommend:
TDD by example, GOOS and Jason Gorman's TDD book

How to model Region and a point in that region?

I need to model a Region that has a contains(point) method. That method determines whether a point falls within the boundaries of the Region.
I currently see two implementations of Region:
One where the region is defined by a start and end postalcode.
One where the region is defined by a lat/lng and a radius.
Now, my main problem is how to define the interface for the contains() method.
Possible solution #1:
One easy solution is to let a point also be defined by a Region:
PostalcodeRegion implements Region
region = new PostalcodeRegion(postalStart: 1000, postalEnd: 2000);
point = new PostalcodeRegion(postalStart: 1234, postalEnd: 1234);
region.contains(point); // true
The interface could look like this:
Region
+ contains(Region region):bool
The problem with this is that the contains() method is not specific, and that we abuse Region to let it be something it is not: a Point.
Possible solution #2:
Or, we define a new point class:
PostalcodeRegion implements Region {}
PostalcodePoint implements Point {}
region = new PostalcodeRegion(postalStart: 1000, postalEnd: 2000);
point = new PostalcodePoint(postalCode: 1234);
region.contains(point); // true
Interface:
Region
+ contains(Point point)
There are several problems with this method:
contains() method is still not specific
There is a pointless Point concept. In and of itself it is/does nothing, it is just a marker interface.
Clarification:
Ok, so this is the first time I encounter where I provide my line of thinking, in the form of possible solutions, that is actually counter productive. My apologies.
Let me try and describe the use case: The system this use case is part of is used to handle insurance claims (amongst other things). When someone claims water damages from a leaking pipe f.e., this system handles the entire workflow from entry by the customer, all the way to sending a repair company etc to close the file.
Now, depending on circumstances, there are two ways to find eligible repair companies: by postal code, or by lat lng.
In the first case (postal code), we could find eligible repair companies with the following code:
region = new PostalCodeRegion(customer.postalCode - 500, customer.postalCode + 500)
region.contains(new PostalCodePoint(repairCompany1.postalCode))
region.contains(new PostalCodePoint(repairCompany2.postalCode))
Or, in the second case:
region = new LatLngRegion(customer.latLng, 50) // 50 km radius
region.contains(new LatLngPoint(repairCompany1.latLng))
region.contains(new LatLngPoint(repairCompany2.latLng))
I want to be able to safely pass around Regions and Points, so I can make sure they are Regions and Points. But I don't actually care about their sub-types.
One thing I would like, but I am not sure it is possible, is to not have to do a runtime check on the passed point in the contains() method. Preferably it would be enforced by contract that I get the correct data (fitting to the chosen Region implementation) to work with.
I'm mostly just thinking out loud. I am inclined to go with method #2, and do a runtime type check of the passed point var in contains() implementation.
I would like to hear some thoughts over one or the other, or even better: a new suggestion I haven't thought of.
It shouldn't be really relevant, but the target platform is PHP. So I can't use generics for example.
Given that a Region would have to operate on two abstractions that have nothing in common (Point and Postcode) then a generic interface is one way of crafting a clean strongly typed common interface, but you should question whether that abstraction is useful to model or not. As developers it's easy to get lost in too much abstractions e.g. maybe a Region<T> is just a Container<T>, etc. and all of a sudden the concepts you work with are nowhere to be found in your domain's Ubiquitous Language.
public interface Region<T> {
public boolean contains(T el);
}
class PostalRegion implements Region<Postcode> {
public boolean contains(Postcode el) { ... }
}
class GeographicRegion implements Region<Point> {
public boolean contains(Point el) { ... }
}
The issue with such question is that it's focusing on how to achieve a specific design rather than explaining the real business problem and that makes it difficult to judge whether or not the solution is appropriate or which alternate solution would.
How would the system leverage the common interface if such interface was implemented? Would it make the model easier to work with?
Since we are forced to assume a problem domain, here's a fictional scenario about developing a city zonage system (I know nothing about this domain so the example may be silly).
In the context of city zonage management, we have uniquely
identified regions that are defined by a postal code range and a
geographical area. We need a system that can answer whether or not a
postal code and/or a point is contained within a specific region.
That gives us a little more context to work with and come up with a model that can fulfill the needs.
We can assume that an application service such as RegionService could maybe look like:
class RegionService {
IRegionRepository regionRepository;
...
boolean regionContainsPoint(regionId, lat, lng) {
region = regionRepository.regionOfId(regionId);
return region.contains(new Point(lat, lng));
}
boolean regionContainsPostcode(regionId, postcode) {
region = regionRepository.regionOfId(regionId);
return region.contains(new Postcode(postcode));
}
}
Then, maybe the design would benefit from applying the Interface Segregation Principle (ISP) where you'd have a Locator<T> interface or explicit PostcodeLocator and PointLocator interfaces, implemented either by Region or other services and used by the RegionService or be a service of their own.
If answering the questions requires complex processing, etc. then maybe the logic should be extracted from a PostalRange and an Area. Applying the ISP would help keeping the design more flexible.
It's important to note that a domain model shines on the write side to protect invariants and compute complex rules & state transitions, but querying needs are often better expressed as stateless services that leverages powerful infrastructure components (e.g. database).
EDIT 1:
I had not realized you mentioned "no generics". Still leaving my answer there b/c I think it still gives good modeling insights and warns about not so useful abstractions. Always think about how the client will be using the API as it helps to determine the usefulness of an abstraction.
EDIT 2 (after clarification added):
It seems that the Specification Pattern could be a useful modeling tool here.
Customers could be said to have a repair company eligibility specification...
E.g.
class Customer {
...
repairCompanyEligibilitySpec() {
//The factory method for creating the specification doesn't have to be on the Customer
postalRange = new PostalRange(this.postalCode - 500, this.postCode + 500);
postalCodeWithin500Range = new PostalCodeWithinRange(postalRange);
locationWithin50kmRadius = new LocationWithinRadius(this.location, Distance.ofKm(50));
return postalCodeWithin500Range.and(locationWithin50kmRadius);
}
}
//Usage
repairCompanyEligibilitySpec = customer.repairCompanyEligibilitySpec();
companyEligibleForRepair = repairCompanyEligibilitySpec.isSatisfiedBy(company);
Note that I haven't really understood what you mean by "I want to be able to safely pass around Regions and Points" or at least failed to understand why this requires a common interface so perhaps the proposed design wouldn't be suitable. Making the policy/rule/spec explicit has several advantages and the specification pattern is easily extensible to support features such as describing why a company was not eligible, etc.
e.g.
unsatisfiedSpec = repairCompanyEligibilitySpec.remainderUnsatisfiedBy(company);
reasonUnsatisfied = unsatisfiedSpec.describe();
Ultimately the specification itself doesn't have to implement the operations. You could use the Visitor Pattern in order to add new operations to a set of specifications and/or to segregate operations by logical layer.
I think it's better not to have the implementation of contains in the data object and to create a seperate class for each of the contains implementations. Something like:
class Region
{
...
}
class RegionCheckManager
{
function registerCheckerForPointType(string $pointType, RegionCheckerInterface $checkerImplementation): void
{
...
}
function contains(PointInterface $point, Region $region): bool
{
return $this->getCheckerForPoint($point)->check($region, $point);
}
/** get correct checker for point type **/
private function getCheckerForPoint(PointInterface $point): RegionCheckerInterface
{
...
}
}
interface RegionCheckerInterface
{
public function contains(PointInterface $point): bool;
}
class PostcodeChecker implements RegionCheckerInterface
{
...
}
class PointChecker implements RegionCheckerInterface
{
...
}
Postcode and Point are different conceptual things, they are two different types. Postcode is a scalar value, Point is a geographic item. In fact, your PostalCodeRegion class is a range of scalar value, your LatLngRegion class is a geographic area that has center coordinates and radius. You try to combine two incompatible abstractions. Attempt to make one interface for two absolutely different things is the wrong way which leads to unobvious code and implicit abstractions. You should rethink your abstractions. For example:
What is a postcode? It is a positive number in the simplest case. You can create a Postcode class as a value object and implement simple methods to work with its data.
class Postcode
{
private $number;
public function __constuct(int $number)
{
assert($value <= 0, 'Postcode must be greater than 0');
$this->number = $number;
}
public function getNumber(): int
{
return $this->number;
}
public function greatOrEqual(Postalcode $value): bool
{
return $this->number >= $value->getNumber();
}
public function lessOrEqual(Postalcode $value): bool
{
return $this->number <= $value->getNumber();
}
}
What is a postcode range? It a set of postcodes that contains start postcode and end postcode. So you can also create a value object of a range and implement contains method in it.
class PostcodeRange
{
private $start;
private $end;
public function __construct(Postcode $start, Postcode $end)
{
assert(!$start->lessOrEqual($end));
$this->start = $start;
$this->end = $end;
}
public function contains(Postcode $value): bool
{
return $value->greatOrEqual($this->start) && $value->lessOrEqual($this->end);
}
}
What is a point? It is a geographic item that has some coordinates.
class Point
{
private $lan;
private $lng;
public function __constuct(float $lan, float $lng)
{
$this->lan = $lan;
$this->lng = $lng;
}
public function getLan(): float
{
return $this->lan;
}
public function getLng(): float
{
return $this->lng;
}
}
What is an area? It is a geographic region that has some borders. In your case, those borders defined with a circle that has a center point and some radius.
class Area
{
private $center;
private $radius;
public function __constuct(Point $center, int $radius)
{
$this->center = $center;
$this->radius = $radius;
}
public function contains(Point $point): bool
{
// implementation of method
}
}
So, each company has a postcode and some location defined by its coordinates.
class Company
{
private $postcode;
private $location;
public function __construct(Postcode $postcode, Point $location)
{
$this->postcode = $postcode;
$this->location = $location;
}
public function getPostcode(): Postcode
{
return $this->postcode;
}
public function getLocation(): Point
{
return $this->location;
}
}
So, how you said you have a list of companies and try to find it by postcode range or area. So you can create company collection which can contain all companies and can implement algorithms to search by necessary criteria.
class CompanyCollection
{
private $items;
public function __constuct(array $items)
{
$this->items = $items;
}
public function findByPostcodeRange(PostcodeRange $range): CompanyCollection
{
$items = array_filter($this->items, function(Company $item) use ($range) {
return $range->contains($item->getPostcode());
});
return new static($items);
}
public function findByArea(Area $area): CompanyCollection
{
$items = array_filter($this->items, function(Company $item) use ($area) {
return $area->contains($item->getLocation());
});
return new static($items);
}
}
Example of usage:
$collection = new CompanyCollection([
new Company(new Postcode(1200), new Point(1, 1)),
new Company(new Postcode(1201), new Point(2, 2)),
])
$range = new PostcodeRange(new Postcode(1000), new Postcode(2000));
$area = new Area(new Point(0, 0), 50);
// find only by postcode range
$collection->findByPostcodeRange($range);
// find only by area
$collection->findByArea($area);
// find by postcode range and area
$collection->findByPostcodeRange($range)->findByArea($area);
If I understand the problem correctly, you have some module M, which needs to accept some 3 objects:
implementation of region (postcodes vs radius, let's call them R1 vs R2)
implementation of point (postcode vs lat/lng, P1 vs P2)
some API C to check the point is within the region
and it then applies the 3rd object on the first 2.
(Could be that C is R1 or R2, that's immaterial for the problem definition).
So spelling out the problem: you can apply C on R1+P1 or R2+P2, but not R1+P2 or R2+P1.
I'm afraid the only way to implement it in a type-safe manner is as follows:
C is an interface, apply().
C1 implements C, and has fields of type R1, P1.
C2 implements C, and has fields of type R2, P2.
The caller builds either C1 or C2, passes it to M, and M calls c.apply().
Note how M doesn't even see points, only the checker interface C. That's because there is nothing common between P1 and P2 that anyone other than then C can use.

Why is it not possible to access a static field from a class instance?

In my understanding, a static member belongs to the class rather than to a specific instance of that class. It can be useful if either all instances share this specific characteristic with the exact same value, or if I do not want to create any instances of the class at all.
So, if I have a class Car, and all my cars will always have exactly 4 wheels, I could store the number of wheels as a static member of the class Car rather than as a instance variable of a myCar class instance.
But why should it be not possible in Haxe to access the static variable from a class instance? Doesn't make any sense to me.
class Car
{
public static var noOfWheels:Int = 4;
public static function getNoOfWheels():Int
{
return Car.noOfWheels;
}
}
class Main
{
static function main()
{
myCar = new Car();
trace (myCar.noOfWheels);
trace (myCar.getNoOfWheels());
trace (Type.getClass(myCar).noOfWheels);
}
}
Neither of those traces lead to the desired result. The first and second trace result in an error of the type:
Cannot access static field XY from a class instance
while the third leads to:
Class <Car> has no field noOfWheels
Edit for clarification:
I have several child classes of the Car class, inheriting all its properties. In some cases, like the class ItalianVan, I declare the static variable noOfWheels again, thus overshadowing the original Car.noOfWheels.
class ItalianVan extends Car
{
public static var noOfWheels:Int = 3;
}
Now, if I have an arbitrary car instance, I would like to know how many wheels it has. If I access the Car.noOfWheels, the answer would always be 4 wheels, even if that special car actually was a three-wheeled italian van.
Maybe the answer is: Don't use static variables for stuff like that!
But it isn't obvious to me why.
Seems unnecessary to make noOfWheels an instance variable, if all members of that class have the same number of wheels.
I've never used Haxe but I can see that you are accessing to the myCar variable.
Try this:
trace (Car.noOfWheels);
trace (Car.getNoOfWheels());
When you want to access to a static variable you should use the class name.
To access a static variable from an instance maybe you can add a non static method that returns the result of the static call.

OO Software desing handling constraints - which design pattern to use?

I'm looking at a well-known problem and therefore there has to be a design pattern or a mix of patterns to solve it.
With the following classes and properties:
CTask
Name
Duration
TaskArea
CTaskArea
Name
CPerson
Name
Abilities
CAbility
Name
CTool
Name
CleaningTime
CConstraint
Name
Constraint
CTask, CPerson, CTool could have constraints e.g. Task A could only be done by persons with ability X, or person A could not do tasks of TaskArea X and so on.
For example, when I create a new CTask, CPerson or CTool I could imagine a constraint config dialog with dropdowns like:
Class | Operator | Class | Property | Value
CPerson | NOT | CTool | Name | Hammer
What design pattern provides the opportunity to dynamically configure constraints for all the classes, without forcing the classes to know additional information or take additional dependencies on each other?
Can I use an interface for objects to express that they accept constraints being applied somehow, or to discover classes which should be configurable with constraints?
Why not to have contraints_for_xxx property at each object having a constraint for particular xxx property?
When some child property is to be added into a collection, it is first run through constraints collection. If any constraint item returns false... exception is thrown, heaven thunders etc.
Constraints can be filled in object's constructor or later via some setupConstraints() call.
CPerson can look like (PHP example):
class Person
{
protected $constraintsAbc = null;
public function setConstraintsAbc(array $constraints)
{
$this->constraintsAbc = $constraints;
}
public function setABC($value)
{
foreach ($this->constraintsAbc as $constraint) {
if (!$constraint->isValid($value)) {
throw new Exception("Constraint {$constraint->getName()} is not happy with value $value");
}
}
$this->abc = $value;
}
}
class PersonSetup
{
public function setupPerson(Person $person)
{
$constrains[] = new PersonAbcConstraint("Value > 5");
$person->setContraintsABC($constrains);
}
}
This is, of course, fictious example. There is a problem here in some code duplication since you have constraintsAbc, setConstraintsAbc and setAbc as different hard-coded fields. But you can abstract this into some virtual "constraintable" field collection if you like.
this is the solution im ok with:
class CCouldHaveConstraints_Base
{
public virtual GetInstance();
public virtual GetClassName();
public virtual GetPropertyListThatCouldHaveConstraints();
}
class CPerson : CCouldHaveConstraints_Base
{
private String m_PersonName;
private String m_PersonAge;
public String PersonName
{
get {return this.m_PersonName;}
set {this.m_PersonName=value;}
}
public String PersonAge
{
get {return this.m_PersonAge;}
set {this.m_PersonAge=value;}
}
public override GetInstance()
{
return new CPerson;
}
public override GetClassName
{
return "Person";
}
public list<string> GetPropertyListThatCouldHaveConstraints()
{
list <string> ConstraintPropsList = new list<string>;
ConstraintPropsList.Add ("PersonName")
}
}
// class contains a list of all objects that could have constraints
class CConstraint_Lst
{
private list<CConstraint> m_ListOfConstraints;
private list<CCouldHaveConstraints_Base> m_ListOfObjectsThatCouldHaveConstraints;
}
// e.g Person | Person.Name | Tim | NOT | Tool | Tool.Name | "Hammer"
class CConstraint
{
private String m_ClassName_A;
private String m_ClassProperty_A;
private String m_ClassProperty_A_Value;
private String m_Operator;
private String m_ClassName_B;
private String m_ClassProperty_B;
private String m_ClassProperty_B_Value;
}
Is that enough code to figure out how im thinking?
Regards,
Tim
You've already made a great conceptual leap to model the constraints as CConstraint objects. The remaining core of the question seems to be "How do I then organize the execution of the constraints, provide them with the right inputs, and collect their outputs? (the outputs are constraint violations, validation errors, or warnings)"
CConstraints obviously can't be evaluated without any input, but you have some choices on how exactly to provide them with input, which we can explore with questions:
Do they get given a 'global state' which they can explore and look for violations in?
Or do they get given a tuple of objects, or object graph, which they return a success or failure result for?
How do they signal constraint violations? Is it by throwing exceptions, returning results, adding them to a collection of violations, or removing violating objects from the world, or triggering repair rules?
Do they provide an "explanation" output that helpfully explains which object or combination of objects is the offending combination, and what rule it violates?
Compilers might be an interesting place to look for inspiration. We know a good compiler processes some complicated input, and produces one or more easy-to-understand error messages allowing the programmer to fix any problem in their program.
Compilers often have to choose some pattern of organizing the work that they're doing like recursion (recursive descent), or a visitor pattern (visit a tree of objects in some arrangement), or stateful pattern matching on a stream of input approach (syntax token recognition by regex matching, or processing a stream of characters), or a chain-of-responsibility (one processor validates and processes input, passes it to the next processor in the chain). Which is actually a whole family of design patterns you can choose from.
Probably one of the most flexible patterns to look at which is useful for your case is the visitor pattern, because you can extend your domain model with additional classes, all of which know how to do a 'visiting' phase, which is basically what 'validation' often entails - someone visits all the objects in a scenario, and inspects their properties, with an easily extensible set of logics (the validation rules) specific to those types of objects, without needing to worry about the mechanics of the visiting procedure (how you traverse the object graph) in each validation rule.

Changing Class Variables in runtime?

Let me give an idea of what I wish to do: I have a structure or class called student, which contains variables like
int roll_no
and
int reg_no
If the user wishes to add a new variable like char name at run time how can it be done?
Based on the word "Structure" and the variable declarations, I'm going to guess this question is about some flavor of C. How exactly to do this will depend on the language, but as a general rule, if the language is compiled (e.g. C/C++, Java), this is not possible. If the language is interpreted (e.g. Python), this might sort of be possible, like this:
class MyObj:
message = "Hi there"
a = MyObj() # Creating a new instance variable
a.name = "Bill" # Adding a new attribute
Here we've added the name attribute to the a object only, and not the entire class. I'm not sure how you're go about that for the whole class.
But really, the answer to your question is "Don't". You should think about your program and the objects you're using enough to know what fields you will and won't need. If you'll want to have a name field at some point in your program, put it in the class declaration. If you don't want it to have a value on object creation, use a sensible default like null.
Edit
Based on your comments, there are a couple of ways to approach this. I'm still not entirely clear on what you want, but I think one of these cases should cover it. Of the languages I know, Python is the most flexible at runtime:
Python
In Python, a class is just another kind of object. Class variables (check out this question too) belong to the class itself, and are inherited by any instances you create:
class MyObj:
a = 2 # A class variable
b = "a string" # Another one
ObjInstance = MyObj() # Creating an instance of this class
print ObjInstance.a # Output: "2"
ObjInstance.a = 3 # You can access and change the value of class variables *for this instance*
print MyObj.a, ObjInstance.a # Outputs "2 3". We've changed the value of a for the instance
MyObj.c = (3,4) # You can add a new class variable at runtime
# Any instance objects inherit the new variable, whether they already exist or not.
print MyObj.c, ObjInstance.c # Outputs "(3, 4) (3, 4)"
You can use this to add attributes to every instance of your class, but they will all have the same value until you change them. If you want to add an attribute to just one instance, you can do this:
ObjInstance.d = "I belong to ObjInstance!"
print ObjInstance.d # Output: "I belong to ObjInstance!"
print MyObj.d # Throws "AttributeError: class MyObj has no attribute 'd'"
One drawback to using Python is that it can be kinda slow. If you want to use a compiled language it will be slightly more complicated, and it will be harder to get the same functionality that I mentioned above. However, I think it's doable. Here's how I would do it in Java. The implementation in C/C++ will be somewhat different.
Java
Java's class attributes (and methods) are called (and declared) static:
class MyObj {
public static int a = 2;
public static String b = "a string";
}
static variables are normally accessed through the class name, as in Python. You can get at them through an instance, but I believe that generates a warning:
System.out.println(MyObj.a); //Outputs "2"
MyObj ObjInst = new MyObj();
System.out.println(ObjInst.a); //Outputs "2" with a warning. Probably.
You can't add attributes to a Java object at runtime:
ObjInst.c = "This will break"; // Throws some exception or other
However, you can have a HashMap attribute, static or not, which you can add entries to at runtime that act like attributes. (This is exactly what Python does, behind the scenes.) For example:
class MyObj {
private HashMap<String, Object> att = new HashMap<String, Object>();
public void setAttribute(String name, Object value) {
att.put(name, value);
}
public Object getAttribute(String name) {
return att.get(name);
}
}
And then you can do things like:
ObjInst.setAttribute("name", "Joe");
System.out.println(ObjInst.getAttribute("name"));
Notice that I did not declare att static above, so in this case each instance of the MyObj class has this attribute, but the class itself does not. If I had declared it static, the class itself would have one copy of this hash. If you want to get really fancy, you can combine the two cases:
class MyObj {
private static HashMap<String, Object> classAtt = new HashMap<String, Object>();
private HashMap<String, Object> instAtt = new HashMap<String, Object>();
public static void setClassAttribute(String name, Object value) {
classAtt.put(name, value);
}
public void setInstAttribute(String name, Object value) {
instAtt.put(name, value);
}
public Object getAttribute(String name) {
// Check if this instance has the attribute first
if (this.instAtt.containsKey(name) {
return instAtt.get(name);
}
// Get the class value if not
else {
return classAtt.get(name);
}
}
}
There are a few details I've left out, like handling the case of the HashMaps not having the value you're asking for, but you can figure out what to do there. As one last note, you can do in Python exactly what I did here in Java with a dict, and that might be a good idea if the attribute names will be strings. You can add an attribute as a string in Python but it's kind of hard; look at the documentation on reflection for more info.
Good luck!