Reputation: 89
class foo{
Bar b;
}
class bar{
Class clazz = foo.class;
}
Does the above snippet show a cyclic dependency. Class foo has a reference of bar class object. Class bar has reference to foo class itself.
Upvotes: 0
Views: 53
Reputation: 4010
While the specifics can be slightly different depending on the language you use, in more pure object oriented terms, no.
It can be helpful to look at Smalltalk-inspired languages like Ruby to see how this is the case:
class Foo
def initialize()
@b = Bar.new()
end
def what_is_b() # instance method can call class method who
@b.who()
end
def who()
"foo instance"
end
def self.who() # class method can't call instance method what_is_b
"foo class"
end
end
class Bar
def initialize()
@clazz = Foo
end
def what_is_clazz()
@clazz.who()
end
def who()
"bar instance"
end
def self.who()
"bar class"
end
end
f = Foo.new()
puts f.who()
puts f.what_is_b()
puts " and "
b = Bar.new()
puts b.who()
puts b.what_is_clazz()
This outputs:
foo instance
bar instance
and
bar instance
foo class
This shows that a foo instance
has-a bar instance
, and a bar instance
has-a foo class
. In pure OO, a foo class
is a factory for foo instances
, and class methods cannot reference instances methods, but the reverse is true, so foo instances
can depend on foo class
but not the other way around.
So in this contrived example, foo instance
is the head of the dependency tree, while foo class
is the tail. If instead of referencing the Foo class in the clazz instance variable you referenced a foo instance
you would have a cyclic dependency graph
Upvotes: 1