Java class

Explain the features of Java class. Explain Fields, Methods, and Access Levels.

A Java class has attributes, static blocks, non-static blocks, constructors, methods and inner classes.

Fields: Fields are referred to data members whom are to be accessed by the methods, constructors of the same class and methods of other classes.

1. A class can have only copy of fields
2. An object can share group of fields, each per object.

Methods: Methods are executable blocks which has certain process instructions Methods can be static – one copy per class, and can be non-static – one copy per object

Access Levels: Java has the following access levels:

private: The private members can be accessed only by the class
public: The public members can be accessed by any other classes, across packages
protected: The protected members can be accessed by the class, all of sub classes of the current package.

No scope definition: The members with no scope definition can be accessed only by the package in which the class was defined.

Write a sample Java class with explanation.

The following is a code for displaying Hello! World!
public class HelloWorld
{
   public void showHelloWorld()
   {
      System.out.println(“Hello! World!!”);
   }
}
The code must be written in any text editor and the file name should be HelloWorld.java

The code starts with class definition

The method showHelloWorld() has statement to display Hello! World!!

The statement System.out.println(“Hello! World!!”); is to display Hello!World!! on the screen.

The closing braces are to close method block and class definition respectively.

Create the class HelloWorld object in public static void main(String args[]) of another class and invoke the method showHelloWorld().

The following code is the definition of initial class - which has public static void main(String args[])
public class MainHelloWorld
{
   public static void main(String args[])
   {
      HelloWorld helloWrld = new HelloWorld();
      helloWrld.showhelloWorld();
   }
}
The code starts with class definition – public class MainHelloWorld

The method ‘ public static void main(String args[]) ‘ creates object of HelloWorld class and invokes the method showHelloWorld()

After compiling both the classes, JVM should be invoked by identified by the initial class name

1. C:\...\.....> java MainHelloWorld from command prompt of Windows / DOS
2. $> java MainHelloWorld from terminal of Linux / Unix

JVM can identify only ‘public static void main(String args[]) ‘ in the initial class MainHelloWorld

What are accessors and mutator methods in a Java class? Explain with example for each.

Accessors and mutators are used to enforce data encapsulation

Accessor Methods

Accessor methods are used to return values of private fields
The naming convention of accessor method is to prefix the word “get” to the method name.

Example
public String getLastName()
{
   return firstName;
}
Accessor methods always returns same data types for private fields
The following code snippet shows how accessor methods are used.
public class Person
{
   //Private fields
   private String firstName;
   private String middleNames;
   private String lastName;
   private String address;
   private String username;

  //Constructor method
   public Person(String firstName, String middleNames, String lastName, String address)
   {
     this.firstName = firstName;
     this.middleNames = middleNames;
     this.lastName = lastName;
     this.address = address;
     this.username = "";
   }

  //Accessor for firstName

   public String getFirstName()
   {
      return firstName;
   }

  //Accessor for middleNames
   public String getMiddlesNames()
   {
      return middleNames;
   }

  //Accessor for lastName
   public String getLastName()
   {
      return lastName;
   }
}

The initial class for the above code is

public class PersonExample
{
   public static void main(String[] args)
   {
      Person harry = new Person("Harry", "Mathew Shannon", "Davidson", "12 Pall all");
      System.out.println(harry.getFirstName() + " " + harry.getMiddlesNames() + " " + harry.getLastName());
   }
}
Mutator Methods

1. A mutator method is to set a value to a private field

2. The naming convention of mutator method is to prefix the word “set” to the method name.

Example
public String setFirstName(String firstName)
{
     this.firstName=return firstName;
}

3. Mutator methods always sets same data types for private fields

4. The following code snippet shows how mutator methods are used.
public class Person
{
    private firstName, middleName, lastName;
    //Mutator for firstName
    public void setFirstName(String firstName){
    this.firstName = firstName;
}

    //Mutator for middleName
    public void setMiddleName(String middleName)
    {
      this.middleName = middleName;
    }

    //Mutator for lastName
    public void setLastName(String lastName)
    {
      this.lastName = lastName;
    }
5. Mutator methods accept a parameter which the same data type of their corresponding private field

6. The parameter is used to set the private field’s value. It is now possible to modify the values for the address and username inside the Person object:

7. Now the values of the private fields can be modified
The following initial class illustrates the use of mutator methods:
public class PersonExample
{
   public static void main(String[] args)
   {
       Person fedrick = new Person("Fedrick", "Paul", "John");
       fedrick.setMiddleName("Kennedy");
   }
}

Explain the importance of 'this' reference. Write a code to depicts the use of 'this' reference

The ‘this’ reference is used to refer to the current object, i.e., the object whose methods are invoked

‘this’ is used within an instance method or constructor

Any instance variable within an instance method by using the key word ‘this’

When a field is shadowed by a method or a constructor parameter, the use of ‘this’ is quite common

The following code depicts the use of ‘this’:
public class Employee
{
    int empId;
    float salary;
    public void setValues ( int empId, float salary)
    {
       this.empId = empid;// empId – parameter,this.empId - instance variable
       this.salary = salary;// salary – parameter, this.salary - instance variable
    }
}

Explain static variables and static methods in Java. Provide an example to explain them.

1. The static variables and methods are belongs to the class but not to the object

2. Each class will have one copy of static variables and methods

3. Static members are not part of the objects of the class that instantiates

The following example depicts the use of static members
public class MyUtilitiy
{
    public static double mean(int[] readings)
    {
       int sum = 0; // sum of all the elements
       for (int index=0; index       {
          sum += readings[index];
       }
     return ((double)sum) / readings.length;
}//endmethod mean
4. Mean is a static method and can be invoked as ‘MyUtility.mean(readings);‘

5. The objects of MyUtility class will not have a copy of mean() method

6. All the methods in java.lang.Math class are static methods. Ex: Math.sqr()

7. Like static methods, static variables are also belongs to the class.

8. Very common use of static variables is to define constants with keyword ‘final’ Ex: Math.PI, Color.RED
Java constructors
Java constructors - What is a constructor? Explain the differences between methods and constructor, Differences between constructors and methods, Write code to depict the use of constructor...
Java class member
Java class member - What is instance members?, What is instance variable?, What is instance method?, What is static member?, What is static variable?...
Java packages
Java packages - What are Java packages? Explain the importance of Java packages., Steps for creating a package in Java, Explain the packages access specifier, i.e. private, protected, public, default...
Post your comment