Objects

11 0 0
                                    

=================================================public class YourHeightWeight {
private double height;
private double weight;
public YourHeightWeight(double h, double w){
height = h;
weight = w;
}
public void changeHeightWeight(YourHeightWeight hw, double h, double w){
hw.height += h;
hw.weight += w;
}
public void displayHeightWeight(){
System.out.println("height: " + height);
System.out.println("weight: " + weight);
}
}public class PracticeMay20 {
public static void main(String[] args){
YourHeightWeight hw = new YourHeightWeight(170.5, 150);
hw.displayHeightWeight();
hw.changeHeightWeight(hw, 2.5, 3.0);
hw.displayHeightWeight();
}
}====================================

Creating objects

1. declaration - this is simply declaring a variable to be of type of that class. So, when you declared that variable, you are referencing that variable as an object of that class.

     example:

     YourHeightWeight hw

2. instantiating a class - this is simply means creating an object or creating an instance of that class by using the new keyword followed by a constuctor.

    example:

    new YourHeightWeight(170.5, 150);

3. initializing an object - this is simply means that you provide the initial value that is required when creating an object. Like for example if the constructor requires you to provide a String parameter, then, you simply need to provide a string when you instantiate that class to initialize it. Instantiating and initializing are being done at the same time.

4. Referencing an object - this is simply means that you are going to use the reference variable to access the fields and methods to be use so that you can make use of your object. To use the reference, you just state the object name followed by the dot operator and then followed by either the field or method. Note that if it is a method, the parenthesis always comes with the method name even if it has no parameters inside.

    example:

    hw.displayHeightWeight();

5. Objects for garbage collection - these are objects that are goes beyond their scope or becomes null or it is an object that you no longer uses. These are kind of objects that were subjected to garbage collection to free up the memories that it occupies.


Java ProgrammingWhere stories live. Discover now