Showing posts with label reference types. Show all posts
Showing posts with label reference types. Show all posts

Wednesday, 19 February 2014

Covariant return type

An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type.

Example
class Animal{
 String name;

 void setName(String name){
  this.name = name;
 }

 Animal getAnimal(){
  return this;
 }
}

class Tiger extends Animal{
 String name;

 void setName(String name){
      this.name = name;
 }

 Tiger getAnimal(){
      System.out.println("I am tiger and my Name is " + name);
      return this;
 }

 public static void main(String args[]){
      Animal anim = new Tiger();
      anim.setName("Aslam");
      anim.getAnimal();
 }
}

Output
I am tiger and my Name is Aslam

As you see the Tiger.java, the return type for the getAnimal() is Tiger, which is a sub class of “Animal”, so the method overridden.

Some points to Remember

1. Covariant types are applicable for reference types, not for primitives
class Animal{
 int getAnimal(){
  return 0;
 }
}

class Tiger extends Animal{
 byte getAnimal(){
  return 0;
 }
}
     
When you tries to compile the class “Tiger”, compiler throws below error
Tiger.java:2: error: getAnimal() in Tiger cannot override getAnimal() in Animal
byte getAnimal(){
^
return type byte is not compatible with int
1 error


Method Overriding                                                 Hiding methods                                                 Home

Monday, 17 February 2014

Interface as Reference Types

Interfaces can be used as Reference types. If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface.
interface Circle{
  double PI = 3.1428;
  double getArea(int r);
}

class MyCircle implements Circle{
  public double getArea(int r){
    return (Circle.PI * r * r);
  }

  public double getPerimeter(int r){
    return (Circle.PI * 2 * r);
  }

  public static void main(String args[]){
    Circle circle1 = new MyCircle();
    System.out.println("Area of the circle is " +circle1.getArea(10));
  }
}
Output
Area of the circle is 314.28

By Assigning an object to the interface type, the reference variable “circle1” call only the methods declared in the interface. Trying to call the methods which are not declared in the interface cause the compiler error.

Example

class MyCircle implements Circle{
  public double getArea(int r){
    return (Circle.PI * r * r);
  }

  public double getPerimeter(int r){
    return (Circle.PI * 2 * r);
  }

  public static void main(String args[]){
    Circle circle1 = new MyCircle();
    circle1.getPerimeter(10);
  }
}


Above program, tries to call the getPerimeter(), which is not declared in the interface Circle. So trying to call this method throws below compiler error.

MyCircle.java:12: error: cannot find symbol
circle1.getPerimeter(10);
^
symbol: method getPerimeter(int)
location: variable circle1 of type Circle
1 error

Interfaces                                                 Implement more than one interface                                                 Home

Friday, 7 February 2014

More About Methods

Methods without returning any value and without parameters
    Syntax:
    void methodName(){
        //body
    }

If a method don't return any value, then it's return type must be void

Example
class MethodEx{
 void print(){
  System.out.println("I am not returning any value");
 }
 
 public static void main(String args[]){ 
  MethodEx obj = new MethodEx();
  obj.print();  
 }
}  

Output
I am not returning any value

Methods without returning any value and with parameters
    Syntax:
    void methodName(parameters){
        //body
    }
    You can give any number of parameters to a method

 Example
class MethodEx{
 void print(int a, int b){ 
  System.out.println("The parameter value is " + a +" " + b);
 }
 public static void main(String args[]){
  MethodEx obj = new MethodEx();
  obj.print(10,20);
 } 
}
 
Output    
 The parameter value is 10 20

Methods with returning a value and without parameters
    Syntax
    returnType methodName(){
        //body
    }
Here returnType is any primitive or reference type. The method must returns the value which is compatible with the returnType of the method.

Example
class MethodEx{
 String fun(){ 
  return "Let's have fun with methods";
 }
 
 public static void main(String args[]){ 
  MethodEx obj = new MethodEx();
  String s = obj.fun();
  System.out.println(s);   
 }
}

Output
Let's have fun with methods

Observation
The method fun() return type is String, so whatever the value returns by the method fun(), we must store it in the String variable like “String s = obj.fun()”.

Methods with returning a value and with parameters
    Syntax
    returnType methodName(parameters){
        //body
    }

A method can have any number of parameters. Here returnType is any primitive or reference type. The method must returns the value which is compatible with the returnType of the method.

Example
class MethodEx{
 String fun(String firstName, String lastName, int age){
  return "I am " + firstName +" " + lastName + " and my Age is " + age;
 }
 
 public static void main(String args[]){
  MethodEx obj = new MethodEx();
  String s = obj.fun("Aravind", "Phaneendra", 25);
  System.out.println(s);
 }
}
        
Output
 I am Aravind Phaneendra and my Age is 25
    
Some Points to Remember
1. returning incompatible value causes the compiler to throw error.
     Example
class MethodEx{
 int sum(int a, int b){
  return 10.01;
 }
}
                  
When you try to compile the above program, compiler will throw the below error

MethodEx.java:4: error: possible loss of precision
 return 10.01;
 ^
 required: int
 found: double
1 error


2. You can call the method in print methods, if it is returning a value, i.e, non void type methods
    Example
class MethodEx{
 int sum(int a, int b){
  return (a+b);
 }
 public static void main(String args[]){
  MethodEx obj = new MethodEx();
  System.out.println("Sum of 10 and 20 is " + obj.sum(10,20));
 }
}

Output
Sum of 10 and 20 is 30
         
3. Calling void methods inside the print causes compile time error
     Example
class MethodEx{
 void print(){
 }
 
 public static void main(String args[]){
  MethodEx obj = new MethodEx();
  System.out.println(obj.print());
 }
} 


When you try to compile the above program, compiler will throw the below error.      
MethodEx.java:7: error: 'void' type not allowed here
 System.out.println(obj.print());
 ^
1 error

           


How to define method                                                 varargs                                                 Home

How to define a method

A method is a programmed procedure that is defined as part of a class. A class (and thus an object) can have more than one method.

Syntax of method definition
    modifier returnType methodName(parameters) Exception List{
        Method Body
    }

Method definition composed of six components :

modifiers : like private, public, protected or default. We have already seen private, public and default. Will discuss more about these in the packages section.

ReturnType : The type of the value written by the method. If you don't want to return any value make the return type as void. Return type will be any primitive type or reference type.

MethodName : The name given to the method

parameters: Method is defined with parameters or with out parameters. A method can be defined with any number of parameters.

Exception List: A Method can throw any number of exceptions, will discuss about this on ExceptionHandling section

Method Body: The actual implementation of the method goes here

Example
    1. public int sum(int a, int b){
        return (a+b);
        }

        modifier : public
        returnType : int
        methodName : sum
        parameters : a,b
        Exception List : none
        Method body : calculates the sum of the two parameters and return the sum.

2. void sayHello(){
        System.out.println(“Hello”);
    }

    modifier : default
    returnType : void
    methodName : sayHello
    parameters :none
    Exception List : none
    Method body : simply prints the message “Hello” to the console.

If no access specifier (modifier) specified to a variable or method, it assumes default access specifier(modifier).

Naming a Method
By convention method names starts with a small character and starting character of subsequent words is capitalized.

    Example:
    walk()
    sleep()
    setColor(String s)
    getHeight()

Local Variables
Variables declared inside a method are called local variables. These are not accessible out side of the method. You must initialize local variables before using.

Some Points to remember
Trying to use local variables before initializing causes compile time error

Example
class LocalVariable{
 int sum(int a, int b){
  int c;
  System.out.println(c);
  return (a+b);
 }
} 

Since “c” is a local variable, when your program tries to access local variable, before initialization, compiler will throw the error.
 
For the above program, you will get below error
LocalVariable.java:5: error: variable c might not have been initialized
            System.out.println(c);
                                          ^
1 error





Instance methods                                                 More about methods                                                 Home