Question

Okay, so what I need help with is the relations between the classes and the methods. I've heard about association and aggregation, but I don't know how to use them, or even if they fit in this code.

Also, I would like to know what super() does and what does p3=p3In in class Pgm2.

public class Pgm1 { 

    public Pgm1() { 
        System.out.println("Konstruktor Pgm1"); 
    } 

    public void skriv() { 
        System.out.println("Skriv i Pgm1"); 
    } 

    public static void main(String[] args) { 
        Pgm3 p3=new Pgm3(); 
        p3.skriv(); 
        Pgm4 p4=new Pgm4(p3); 
        p4.skriv(); 
        Pgm2 p2=new Pgm2(); 
        p2.skriv(); 
    } 

} 

public class Pgm2 { 

    private Pgm1 p1; 

    public Pgm2() { 
        p1=new Pgm1(); 
        System.out.println("Konstruktor Pgm2"); 
    } 

    public void skriv() { 
        System.out.println("Skriv i Pgm2"); 
    } 

} 

public class Pgm3 { 

    public Pgm3() { 
        System.out.println("Konstruktor Pgm3"); 
    } 

    public void skriv() { 
        System.out.println("Skriv i Pgm3"); 
    } 

} 

public class Pgm4 extends Pgm2 { 

    private Pgm3 p3; 

    public Pgm4(Pgm3 p3In) { 
        super(); 
        p3=p3In; 
        System.out.println("Konstruktor Pgm4"); 
    } 

    public void skriv() { 
        System.out.println("Skriv i Pgm4"); 
    } 

}
Was it helpful?

Solution

The classes Pgm1, Pgm2 and Pgm3 are all pretty normal classes. However the class Pgm4 Extends Pgm2 meaning that Pgm4 is a child class of Pgm2. Think of this like a zoo simulator program, you may have one class that is called Animal or something similar, and then a lot of other classes that extend it. Some examples of these classes might me Lion, Tiger, Bear (Oh my) and each of those specific animal classes are animals in the simulator.

The super(); statement (like others have pointed out) calls the constructor of the class that you extend. Finally the p3=p3In; line assigns a variable inside the Pgm4 class to whatever is passed to the class through the constructor. Hope that helps!

OTHER TIPS

super(); calls constructor (without parameters) of base class (in this case, Pgm2).

p3=p3In; assigns value of p3In to class variable p3.

super() 

is a special use of the super keyword where you call a parameterless parent constructor. In general, the super keyword can be used to call overridden methods, access hidden fields or invoke a superclass's constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top