Constructor (object-oriented programming): Difference between revisions

Content deleted Content added
m method.If->method. If - Fix a typo in one click
Tags: Mobile edit Mobile web edit Advanced mobile edit
Type hint
Line 107:
class Example
{
Example() //non Non-parameterized constructor
{
this(1); //calling Calling of constructor
System.out.println("0-arg-cons");
}
Example(int a) //parameterized Parameterized constructor
{
System.out.println("1-arg-cons");
}
}
public static void main(String[] args)
{
Line 538 ⟶ 539:
<source lang="perl6">
class Person {
has Str $.first-name is required; # firstFirst name (a string) can only be set at
# construction time (the . means "public").
has Str $.last-name is required; # lastLast name (a string) can only be set at
# construction time (a ! would mean "private").
has Int $.age is rw; # ageAge (an integer) can be modified after
# construction ('rw'), and is not required
# during the object instantiation.
# createCreate a 'full-name' method which returns the person's full name.
# thisThis method can be accessed outside the class.
method full-name { $!first-name.tc ~ " " ~ $!last-name.tc }
 
# createCreate a 'has-age' method which returns true if age has been set.
# thisThis method is used only inside the class so it's declared as "private"
# by prepending its name with a !
method !has-age { self.age.defined }
# checkCheck custom requirements
method TWEAK {
if self!has-age && $!age < 18 { # noNo under 18
die "No person under 18";
}
Line 592 ⟶ 593:
class Person
{
private string $name;
 
public function __construct(string $name) : void
{
$this->name = $name;
}
 
public function getName() : string
{
return $this->name;