What happens when i do something like this:
$stallion = Horse->new(gender => "male");
$molly = Mule->new(gender => "female");
$colt = $molly->breed($stallion);
I cant comprehend what is going on on that code?
From that example, are there 2 different classes? (Horse class with a new method or constructor, Mule class with another new constructor).
$colt = $molly->breed($stallion);
From that code, my understanding is that $molly is just the same as the Mule class which have other method than new - breed. Am i right?
From that example, are there 2 different classes? (Horse class with a new method or constructor, Mule class with another new constructor).
Quite correct.
Anytime you see an expression of STRING_LITERAL->METHOD_NAME(), that STRING_LITERAL is almost guaranteed to be a class name.
And when you see STRING_LITERAL->new(), unless the person who wrote the code decided to be too smart for their own good, this would be a call to that class' constructor, returning an object of that class. (However, the "new" being a constructor is merely a voluntary convention; there's nothing in Perl enforcing that - someone too smart/dumb COULD have defined "new()" sub to return a value of 2+3 - you have no guarantee aside from looking at the code and testing)
After that example, you get, hopefully:
$stallion - holding a value returned from Horse class constructor - will have as a value an object of class Horse.
$molly - holding a value returned from Mule class constructor - will have as a value an object of class Mule.
What happens when that stallion reference is passed to another instantiation of class?
What happens in $molly->breed($stallion); call - as was answered in yesterday's question, this is an object way of calling a method, so what you do is:
breed() subroutine, which must of course be defined in the class that $molly object belongs to (e.g. be a method in Mule class)breed() subroutine, special list variable @_ will be aliased to elements of this parameter list ($molly, $stallion).And in that code is breed another method in another class?
As noted in a bullet point above, yes, if $molly is an object of a certain class (Mule), an expression $molly->METHOD_NAME() means calling a method of that name that is known (defined or inherited from parent class) in the class of which $molly is an object of.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With