Java Classes and Methods

Java class contains

Class definition
Instance, class, local Variables

Method definition
Name of the method
List of parameters
Body of methods
Return type

Definition of a class

General form of a class
Class classname
{
  type instance-variable1;
  type instance-variable2;
    ....
  type instance-variablen;

  type methodname1(parameter list)
  {
    body of the method
  }

  type methodname2(parameter list)
  {
    body of the method
  }
    ....
  type methodnamen(parameter list)
  {
    body of the method
  }
}

The data or variables within the class are called as instance variables. The data or variables and methods which are within the class are collectively called as members of the class.
variable declaration:

    int x,y;
    char c;
    float m;

Methods

Methods are defined as follows.
They contain

Return type Name of the method (A list of parameters)
{
  Body of the method
}

e.g.:
  void dispValue( )
  {
    int x = 5;
    int y = 10;
    int z;
    z=x+y;
    System.out.println("After addition" + z);
  }

void is the retutn type and dispValue is the name of the method.
The name of the method and list of parameters is called as the signature of the method.

Note 1: Return type of the method is not part of the method's signature.

Note 2: In the above program the declaration of local variables hides (or takes precedence over) the value of instance or class variables. However, the values of instance or class variables can be accessed by using the keyword this along with the variable name.

Example for a class

class Employee
{
  int id;
  float salary;
  String name ;
  void ReadData()
  {
    ....
  }
  void DispData()
  {
    ....
  }
}

Program :

public class PrintPoint
{
  public int x = 5;
  public int y = 10;
  void dispoint()
  {
    System.out.println("Printing the Coordinates");
    System.out.println(x +" "+y);
  }
  public static void main(String args[])
  {
    PrintPoint point = new PrintPoint();
    point.dispoint();
  }
}

Access Modifier

  • private - accessible only within that class
  • protected - accessible only to the sub classes, even across the package
  • public - accessible to all classes, even across the package
  • default - accessible to all the classes within the package

Variables

Local Variable

  • Declared and allocated within a block.
  • Discarded on exit from the block.
  • Not implicitly initialized to a default value and must be explicitly initialized.

Instance Variables

  • Declared outside of any methods.
  • Implicitly initialized to a standard default value.
  • Discarded when the object is garbage collected.

Click here for example


Program :

public class TestThis
{
  int x = 10;
  static int y = 20;
  final int z = 30;
  void dispvalue()
  {
    int x = 5;
    int y = 10;
    int z = 25;
    System.out.println("Printing Local variables");
    System.out.println(x +" " +y+ " "+z);
    System.out.println("Printing Instance variables");
    System.out.println(this.x +" " +this.y + " "+this.z);
  }
  public static void main (String args[])
  {
    TestThis temp = new TestThis();
    temp.dispvalue();
    System.out.println("Printing values in main");
    System.out.println(temp.x+ " "+temp.y+" "+temp.z);
  }
}

Class (static) Variables

  • Local to a class (all objects of that class)
  • Allocated and initialized when the class is loaded
  • Implicitly initialized to a standard default value

Example:
class BankAccount
{
  static int bankID;// class variable.
  int amount, rate; // instance variable
  int balance; // instance variable
  void withdraw(int amt)
  {
    balance -= amt; // local variable
  }
  ....
}

Click here for example

Example: local, instance and static variable

public class LisVariable
{
  int height = 180;
  static float salary = 5000;
  final String name = "Krithika";
  void disp()
  {
   int height = 190;
   float salary = 6000;
   String name = "Gokul";
   System.out.println("\n\nPrinting Local variables");
   System.out.println(height +" " +salary + " "+name);
   System.out.println("\n\nPrinting Instance variables");
   System.out.println(this.height +" " +this.salary + " "+this.name);
  }
  public static void main (String args[])
  {
   LisVariable temp = new LisVariable();
   temp.disp();
   System.out.println("\n\nPrinting values in main");
   System.out.println(temp.height+ " "+temp.salary+" "+temp.name);
  }
}

Instance

Instance methods: Instance methods can be used only with respect to the instance of class.

class MyClass
{
  ......
  void testMethod()
  {
    ......
  }

  public static void main(String args[])
  {

    MyClass cls=new MyClass();
    cls.testMethod();
  }
}

Class methods

  • Class methods do not require an instance of class to make use of methods.
  • Class methods are defined using the key word-"static" in front of the method name.

class MyClass
  {
    .....
  static void testMethod()
  {
    .....
  }
  public static void main(String args[])
  {
    MyClass.testMethod();
  }
}

Program: Instance and static methods

class InstMethods
{
  int i=5;
  float f=55.5f;

  static void dispvalue()
  {
    System.out.println("\n\nThis is static method");
  }
  void disp()
  {
    System.out.println("\n\nWe are testing an instance method");
    System.out.println("\n\nvalues are "+i+" "+f);
  }

  public static void main(String args[])
  {
    InstMethods ob1=new InstMethods();
    //InstMethods.dispvalue();
    dispvalue();
    ob1.disp();
  }
}

Command line arguments:

  • When java application is run with arguments given at the command line, the arguments are stored as an array of strings.
  • The argument array is passed to the main method.

Click here for example

Program: Command Line Argument

class CmdLine
{
  public static void main(String args[])
  {
    int i;
    System.out.println("\n\n"+args.length+ " arguments passed from the command line and they are\n");
    for (i=0;i<args.length;i++)
    {
      System.out.println(i+"="+args[i]+"\n");
    }
  }
}

Method Overloading

  • Name of the method should be same for more than one method and the number of arguments/type of arguments should be different.
  • The return type can be different as long as the method signature is different.

Program for overloading methods

class OvrLoad
{
  public int calc(int x, int y)
  {
    return x+y;
  }
  public float calc(int x, float y)
  {
    return y/x;
  }
  public void calc(int x, String str)
  {
    int twice;
    twice=x * x;
    System.out.println("\n"+str+" " + twice);
  }
  public static void main(String args[])
  {
    OvrLoad ob1=new OvrLoad();
    System.out.println("\nValues added "+ob1.calc(5,6));
    System.out.println("\nValues divided " + ob1.calc(5,6.0f));
    ob1.calc(5,"Square of a value");
  }
}

Method Overriding

  • When an object,s method is called, java looks for the method definition in object's class. If it can not find then it checks one level up in the hierarchy of classes.
  • Consider a case where a method with the same signature is used both in the subclass and in the super class. In this case method defined in the subclass will be invoked. The method of super class is overridden.
  • But if suppose the method defined in the super class to be used then super key word can be used along with the name of the method.

Click here for example 1

Click here for example 2

Inheritance: Sub class

  • If more than one class say class1 and class2 have some properties to be shared, then they could be defined in a single class say class0.
  • Class1 and class2 then can use method definitions and variables from class0 as if they belonged to them.
  • Class1 and class2 are called subclasses and class0 is called as parent class.
  • This concept is called as Inheritance.
  • This is achieved with the help of the keyword extends which will be followed by the name of the superclass.
  • In java only single Inheritance is allowed. That means classes can inherit properties only from one immediate super class.

Click here for example

Program: Subclass, Superclass

class TestSuper
{
  int i;
  long fact=1;
  void factFind(int n)
  {
    for(i=1;i<=n;i++)
    {
      fact=fact*i;
    }
  }
  void disp()
  {
    System.out.println("\n\nFactorial is calculated from super class and it is "+fact);
  }
}
class TestSub extends TestSuper
{
  void display()
  {
    System.out.println("\n\n I am in subclass");
  }
  public static void main(String args[])
  {
    TestSub ob=new TestSub();
    ob.display();
    ob.factFind(4);
    ob.disp();
  }
}

Keyword 'this'

'this' is used to refer to instance variables and methods of the current class.

class Box
{
  int width;
  int height;
  int depth;
  Box(int width, int hieght, int depth)
  {
    this.width = width;
    this.height = height;
    this.depth = depth;
  }
  ....
}

Keyword 'super'

Has 2 forms Calls the superclass' constructors used to access a member of the superclass that has been hidden by a member of a subclass.

class SuperClass
{
  int index;
  SuperClass(String name)
  {
    .....
  }
  ....
}
class Sub extends SuperClass
{
  int index;
  Sub(String s)
  {
    super(s);
    void print(this.index, super.index);
  }
  ....
}

Java Constructor

  • A constructor is the part of your class that helps build you a new instance of that class.
  • A constructor should have the same name as the class.
  • There can be more than one constructor method. But the number or type of arguments has to be different.
  • Constructors do not have return type.
class test
{
  int i, j;
  test()
  {
    i=0;
    j=0;
  }
  test(int x, int y)
  {
    i=x;
    j=y;
  }
  void disp()
  {
    System.out.println("\n i="+i+ "j="+j);
  }
  public static void main(String args[ ])
  {
    test ob1=new test();
    test ob2=new test(6,7);
    ob1.disp();
    ob2.disp();
  }
}

Click here for example

Final classes, methods and variables

The final modifier indicates that the entity cannot be changed.

  • a final class can not be sub classed.
  • a final method can not be overridden by another class.
  • final variable cannot change its value.

Class a
{
  ....
  Final void math()
  {          }
}

Final class a
{
  void math()
  {          }
}

Abstract classes

  • An abstract class has zero or more of its methods which are abstract. i,e; methods which has no body.
  • Subclass has to override such methods by providing method implementation.
  • Abstract class provides guidelines for the properties and methods of an object.
Interface:
  • If all the methods in abstract class are abstract, then it is better to implement as an interface.

Packages

  • It is a collection of classes and interfaces of similar nature.
    Ex: java.io
  • These help us to group together similar classes.
  • These define a boundary to see how classes and interfaces interact with one another.

Importing a Class from an Existing Java Package


import myJava.Account.myAccount; // imports the myAccount class only

                                                  OR

import myJava.Account.*; // imports all classes in Account package

Setting CLASSPATH to Point to Java Classes & Packages

  • If CLASSPATH is not set, java will look for the class in the current directory and default directory (c:\ jdk..\lib)
  • If the CLASSPATH is set then java will look only in those directories specified by the variable CLASSPATH.


Arrays, Sorting and Searching << Previous

Next>>Exception Handling

Our aim is to provide information to the knowledge seekers. 

comments powered by Disqus
Footer1