Δημοσιεύτηκε: 19 Ιαν 2012, 00:01
από giannosfor
Star_Light έγραψε:Owing to constructor chaining , when object of child class DemoChild is created , constructor Demo() of the parent class is invoked first and later constructor DemoChild() of the child is created.

Λογικά άλλαξες το όνομα της κλάσης από Demo σε examples.

Κώδικας: Επιλογή όλων
public class examples
{
int value1 ;
int value2 ;

examples()
{
value1 = 1;
value2 = 2;
System.out.println("Inside 1st Parent Constructor");
}

examples( int a )
{
value1 = a;
System.out.println("Inside 2nd Parent Constructor");
}

public void display()
{
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}

public static void main(String args[]){
DemoChild d1 = new DemoChild();
d1.display();
}
}

class DemoChild extends examples {
int value3;
int value4;

DemoChild()
{
super(5);
value3 = 3;
value4 = 4;
System.out.println("Inside the Constructor of Child");
}

@Override
public void display()
{
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
System.out.println("Value1 === "+value3);
System.out.println("Value2 === "+value4);
}
}


Σε αυτό το παράδειγμα φαίνεται η κληρονομικότητα και το method overloading.
Φυσικά πρέπει να ξέρεις και τι είναι constructor.

Όταν τρέχεις την super που αν την χρησιμοποιήσεις πρέπει να είναι το πρώτο πράγμα καλεί τον constructor της upperclass .Εδώ καλεί τον constructor με το όρισμα διαφορετικά καλείτε αυτόματα ο πρώτος constructor.