Hi all, I am student and in two days I gine exams Java.
I need your help to understand the below exercise.


I have to explain all the lines from class RunParent

class Parent
{
    double value = 0;

    public Parent()
    {
        value = 1.0;
        System.out.println("Parent value " +value);
    }
 

    public Parent(double value)
    {
        System.out.println("Parent value " + value);
    }


    public void setValue (double value)
    {
        this.value -= value;
    }
}
class Child extends Parent
{
    String message;


    public Child (String message)
    {
        this.message = message;
        System.out.println("Child "+message);
    }

     public Child (double value)
    {
            super(value);
            this.value = value++;
            System.out.println("Child value " +value);
     }

     public void setMessage (String message)
     {
           this.message = message;
    }
   
    public void setValue1 (double value)
    {
        this.value += value;
    }

    public void setValue2 (double value)
    {
        super.setValue (--value);
    }
}
public class RunParent
{


    public static void main(String args [])
    {
        Parent P = new Parent();
        Child C1 = new Child(5.5);
        Child C2 = new Child("Second Child");
        System.out.println (C1.value);
        System.out.println (C2.value);
        System.out.println (C1.message);
        System.out.println (C2.message);
        System.out.println (P.value);
        C1.setMessage ("First Child");
        System.out.println (C1.message);
        C2.setValue (7.5);
        System.out.println (C2.value);
        System.out.println (P.value);
        C1.setValue1 (3);
        System.out.println (C1.value);
        C1.setValue2 (8.5);
        System.out.println (C1.value);
    }
}

I am trying to understand and I think that every object has two variables with name value and a variable with name message like that :

Object : C1
Parent value = 5.5
Child value = 6.5

When I run command System.out.println (C1.value) why the result is 5.5 ? I was expecting 6.5 because 6.5 is the value of object.

Also, I have problem to understand the lines
C1.setValue2 (8.5);
System.out.println (C1.value);

Could you help me please ??

For getting 6.5 as value, change the code in class child
line number15 as follows this.value = ++value;
Try it, and reply asap.

Member Avatar for coil

C1.setValue2 (8.5);

This is a basic method call for the method setValue2(...) in the Child class. If you look at the corresponding method, you'll see that the method in Parent is invoked with the keyword super.

The next line basically just displays the updated value.

Thanks a lot

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.