Question

In: Computer Science

Java question: Explain how class (static) variables and methods differ from their instance counterparts. Give an...

Java question:

Explain how class (static) variables and methods differ from their instance counterparts. Give an example of a class that contains at least one class variable and at least one class method. Explain why using a class variable and method rather than an instance variable and method would be the correct choice in the example you select.

Solutions

Expert Solution

thanks for the question,

static class variables belongs to class and not objects of the class, There is only one instance of static variable that gets created per class, whereas we have a set of member variables for each object we create of that class type.

static methods can be invoked either using class name or object reference, but instance methods can only be invoked using object reference.

=============================================================================

We need to create static variables when we want to share data between objects of the class or want to have a value that remains unchanged and can be used by all objects for example constants like PI value or accelaration due to gravity which are constants, we dont need to create an instance of each constant for each object , this will allow us to save some memory consumption which can be avoided if we declare them static.

Below is the simple class Box where i have demonstrated the use of static member variable and method

==============================================================================

public class Box {

    private int length;
    private int width;
    private int height;

    // static variable to track the number of box objects created
    // initialize the value to 0
    private static int boxCount = 0;

    // every time we create a Box object using the default constructor
    // we increment the boxCount by 1
    public Box() {
        length = 0;
        width = 0;
        height = 0;
        // increment the box count value by 1 everytime an object is created
        boxCount += 1;
    }

    // similarly when the overloaded constructor below is called
    // we increment the boxCount by 1
    public Box(int length, int width, int height) {
        this.length = length;
        this.width = width;
        this.height = height;
        // increment the box count value by 1 everytime an object is created
        boxCount += 1;
    }

    // returns the total number of box objects created
    public static int getBoxCount() {
        return boxCount;
    }

    public int getVolume() {
        return getHeight() * getWidth() * getLength();
    }

    public int getHeight() {
        return height;
    }

    public int getWidth() {
        return width;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public static void main(String[] args) {

        // even when no box object is created we can invoke the getBoxCount()
        // method; because we have declared it with static keyword
        // the below line should return 0
        System.out.println("Total Box Objects: " + Box.getBoxCount());
        Box boxOne = new Box();
        // the below line should return 1
        System.out.println("Total Box Objects: " + Box.getBoxCount());
        Box bowTwo = new Box(1, 2, 3);
        // the below line should return 2
        System.out.println("Total Box Objects: " + Box.getBoxCount());
       
    }
}

========================================================================


Related Solutions

Java homework question: Explain how class (static) variables and methods differ from their instance counterparts. Give...
Java homework question: Explain how class (static) variables and methods differ from their instance counterparts. Give an example of a class that contains at least one class variable and at least one class method. Explain why using a class variable and method rather than an instance variable and method would be the correct choice in the example you select.
1. Describe the difference between instance methods and class methods in Java and give an example...
1. Describe the difference between instance methods and class methods in Java and give an example of each. 2. A class variable is visible to and shared by all instances of a class. How would such a variable be used in an application? 3. Describe the difference between abstract classes and concrete classes, giving an example of each. 4. Explain how data are encapsulated and information is hidden in Java? 5. Explain the difference between a class and an interface...
true or false give reason language in java 1.A static inner class can access the instance...
true or false give reason language in java 1.A static inner class can access the instance variables and methods of its outer non-static class 2.executeQuery from statement may return more than one resultset object 3.Connection is java.sql interface that establishes a session with a specific database 4.Writable is an interface in Hadoop that acts as a wrapper class to almost all the primitive data type 5.Text is the wrapper class of string in Hadoop
JAVA programming- answer prompts as apart of one java assignment Static static variables static methods constants...
JAVA programming- answer prompts as apart of one java assignment Static static variables static methods constants Create a class Die representing a die to roll randomly. ☑ Give Die a public final static int FACES, representing how many faces all dice will have for this run of the program. ☑ In a static block, choose a value for FACES that is a randomly chosen from the options 4, 6, 8, 10, 12, and 20. ☑ Give Die an instance variable...
Question: Java Programming. ** Modify Current Program. Current Program class Account{       //instance variables   ...
Question: Java Programming. ** Modify Current Program. Current Program class Account{       //instance variables    private long accountNumber;    private String firstName;    private String lastName;    private double balance;       //constructor    public Account(long accountNumber, String firstName, String lastName, double balance) {        this.accountNumber = accountNumber;        this.firstName = firstName;        this.lastName = lastName;        this.balance = balance;    }    //all getters and setters    public long getAccountNumber() {        return...
Create a Java class named Trivia that contains three instance variables, question of type String that...
Create a Java class named Trivia that contains three instance variables, question of type String that stores the question of the trivia, answer of type String that stores the answer to the question, and points of type integer that stores the points’ value between 1 and 3 based on the difficulty of the question. Also create the following methods: getQuestion( ) – it will return the question. getAnswer( ) – it will return the answer. getPoints( ) – it will...
Create a Java class named Trivia that contains three instance variables, question of type String that...
Create a Java class named Trivia that contains three instance variables, question of type String that stores the question of the trivia, answer of type String that stores the answer to the question, and points of type integer that stores the points’ value between 1 and 3 based on the difficulty of the question. Also create the following methods: getQuestion( ) – it will return the question. getAnswer( ) – it will return the answer. getPoints( ) – it will...
Question 3 A java source module contains the following class with the static methods main and...
Question 3 A java source module contains the following class with the static methods main and procedure1, and the instance method procedure2 (assume given the bodies of procedure1 and procedure2): public class TestQuestion3             {                         static int result, num1 = 10;                         public static void Main( String [ ] args )                         {                                     int [ ] list1 =   { 2, 4, 6, 8, 10}, list2;                                     .    .    .                         }                         static void procedure1( void )                         {                                     .   .   .                         } void procedure2( void )...
JAVA Create an HourlyEmployee class that inherits from Employee and has two new instance variables: hours,...
JAVA Create an HourlyEmployee class that inherits from Employee and has two new instance variables: hours, which represents the hours worked, and wage, which represents the employee's pay per hour. (Both are doubles.) Create a constructor that takes the arguments first name, last name, social security number, hourly wage, and the number of hours worked. Also create accessors, mutators, an earnings method that returns the money earned by the employee this week, and a toString method that returns information about...
(a) What is a class? What is an object? What is the relationship? (b) What are the instance variables and methods of a class?
 (a) What is a class? What is an object? What is the relationship? (b) What are the instance variables and methods of a class? (c) What is the effect of declaring instance variables and methods public or private? (d) Why do we often declare the instance variables of classes private? (e) Could we declare methods private? Would we want to do so?  (f) What does the identifier this mean? Give an example of its use (g) What is a constructor? (h) What is inheritance? Why is...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT