Showing posts with label static methods. Show all posts
Showing posts with label static methods. Show all posts

Friday, 19 January 2018

Kotlin: Companion Objects

By using companion object, you can access the members using the class name (no need to define the object).

HelloWorld.kt
class TestClass {
 companion object {
  fun sayHello() {
   println("Hello")
  }
 }
}

fun main(args: Array<String>) {
 TestClass.sayHello()
}

Output
Hello

As you see above code snippet, I called sayHello function of companion object using TestClass (not created any object to TestClass).

You can give name to companion object.

         companion object FunModules {
                 fun sayHello() {
                          println("Hello")
                 }
         }


HelloWorld.kt
class TestClass {
 companion object FunModules {
  fun sayHello() {
   println("Hello")
  }
 }
}

fun main(args: Array<String>) {
 TestClass.sayHello()
}

Output
Hello


By adding @JvmStatic annotation on top of companion object, you can use it as static member in any java class.


HelloWorld.kt
import kotlin.jvm.JvmStatic

class TestClass {
 companion object {
  @JvmStatic
  fun sayHello() {
   println("Hello")
  }
 }
}

CompanionDemo.java

public class CompanionDemo {
 public static void main(String args[]){
  TestClass.sayHello();
 }
}


Output

Hello


Previous                                                 Next                                                 Home

Friday, 21 February 2014

Abstract Methods and Abstract Classes

Abstract Method
An abstract method is a method that is declared without an implementation. An abstract method is declared using the keyword abstract.

Syntax
abstract returnType methodName(parameters)

Example
abstract int sum(int operand1, int operand2);

Abstract Class
An abstract class is declared using the keyword abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

Syntax
    abstract class ClassName{
        /* may or may not contain abstract methods */
    }

If a class extends the abstract class, then it must provide the implementation for all the abstract methods in the abstract class, otherwise the class should be declared as abstract.

The main purpose of abstract class is to use the common code in the sub classes.

Example
abstract class Animal{
 String name;

 String getName(){
  return name;
 }

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

 abstract String run();
}

class Elephant extends Animal{
 String run(){
  return "I can run at the speed of 25 mph";
 }
}
   
class Lion extends Animal{
 String run(){
  return " I can run at the speed of 50 mph";
 }
}
     
class Tiger extends Animal{
 String run(){
  return "I can run at the speed of 60 mph";
 }
}
     
class AbstractTest{
 public static void main(String args[]){
  Animal anim1 = new Elephant();
  anim1.setName("Gaja");
  System.out.println(anim1.getName() +":" + anim1.run());

  anim1 = new Lion();
  anim1.setName("Aslam");
  System.out.println(anim1.getName() +":" + anim1.run());

  anim1 = new Tiger();
  anim1.setName("PTR");
  System.out.println(anim1.getName() +":" + anim1.run());
 }
}


Output
Gaja:I can run at the speed of 25 mph
Aslam: I can run at the speed of 50 mph
PTR:I can run at the speed of 60 mph

Every Animal has a name, so getName() and setName() are common to all the animals, So the implementation for these methods kept in the abstract class Animal. Where as different Animals runs at different speeds, so the run() method declared as abstract, so all the concrete classes that are extending the class Animal, must provide the implementation for the run method.

Some Points to Remember
1. Can I create constructor inside the abstract class ?
Yes, but you can't initialize an object for the abstract class.

Example
abstract class Animal{
 String name; 

 Animal(String name){
  this.name = name;
 }
}
 
2. Can I make abstract class as final ?
No, If you make abstract class as final, then no other class can able to extend it. So, compiler throws error. Abstract and final can't be used together.

Example
final abstract class Animal{
 String name; 

 Animal(String name){
  this.name = name;
 }
}
 

When you tries to compile the above program, compiler throws the below error.
 Animal.java:1: error: illegal combination of modifiers: abstract and final
    final abstract class Animal{
    ^
    1 error


3. Can I make abstract method as final ?
No, If you make abstract method as final, then no other class can able to override it. So, compiler throws error. Abstract and final can't be used together.

Example
abstract class Animal{
 String name; 

 final abstract void run();

 }
}

When you tries to compile the above program, compiler throws the below error.
Animal.java:4: error: illegal combination of modifiers: abstract and final
final abstract void run();
^
1 error
 

4. Can I define main method in abstract class ?
Yes, it is valid, but creation of object to the abstract is not possible.

Example
abstract class Animal{
 String name; 

 public static void main(String args[]){
  System.out.println("I am in main method");
 }
}
   
Output
I am in main method

5. What is wrong with the below program ?
    abstract class Animal{
        void run();
    }

Above program won't compile, since if you want to make a method as abstract, then it must be declared with the specifier abstract. When you tries to compile, compiler throws the below error.

Animal.java:2: error: missing method body, or declare abstract
void run();
^
1 error

To make the program run you have two options.

Option 1
    Make the method as abstract.

    abstract class Animal{
        abstract void run();
    }

Option 2
provide the implementation for the method run().

    abstract class Animal{
        void run(){
        }
    }
  
6. An abstract class allowed to have static methods, where as interfaces have instance methods only (From Java8 onwards, we can add static methods to interfaces).

7. The methods declared in interface are abstract by default.

8. Can an interface has constructor ?
No

9. Can an abstract class have a final method?
Yes, it can. But the final method cannot be abstract itself

Example
    abstract class Animal{
        final void print(){
            System.out.println(" I am final method in abstract class");
        }
    }


Final Classes and Methods                                                 Abstract Class vs Interface                                                 Home

Thursday, 20 February 2014

Hiding methods

If a subclass defines a class method (static method) with the same signature as a class method in the super class, the method in the subclass hides the one in the super class.

Distinction between Hiding and Overriding
class Animal{
 static void printMsg(){
  System.out.println("I am the super class static method");
 }

 void showMsg(){
  System.out.println("I am the super class instance method");
 }
}

class Tiger extends Animal{
 static void printMsg(){
  System.out.println("I am the sub class static method");
 }

 void showMsg(){
  System.out.println("I am the sub class instance method");
 }

 public static void main(String args[]){
  Animal ref = new Tiger();
  ref.printMsg();
  ref.showMsg();
 }
}

Output
I am the super class static method
I am the sub class instance method

As you observe the output, run time polymorphism not happened for the static method. So the message “I am the super class static method” printed.

The showMsg() method of class Tiger overrides the showMsg() of super class. Where as, the printMsg() of subclass hides the printMsg() of super class.

Remember,A sub class static method always hides the super class static method. Where as sub class instance method overrides the super class instance method.

Some points to remember
1. Can a sub class instance method hides the super class static method?
     No, Compiler error thrown.

Example
class Animal{
 static void printMsg(){
  System.out.println("I am the super class static method");
 }
}
      
class Tiger extends Animal{
 void printMsg(){
  System.out.println("I am the sub class static method");
 }
}
When you try to compile the class Tiger, compiler throws the below error. You will get a compile-time error if you attempt to change an instance method in the superclass to a class method in the subclass, and vice versa.

Tiger.java:2: error: printMsg() in Tiger cannot override printMsg() in Animal
void printMsg(){
^
overridden method is static
1 error

2. What is wrong with the below program ?
class Animal{
 public static void printMsg(){
  System.out.println("I am the super class static method");
 }
}

class Tiger extends Animal{
 static void printMsg(){
  System.out.println("I am the sub class static method");
 } 
} 

The access specifier for an hiding method can allow more, but not less, access than the hidden method. For example, a public static method in the superclass can be made public, but not private, protected and default.

When you tries to compile the class Tiger, compiler throws the below error.

Tiger.java:2: error: printMsg() in Tiger cannot override printMsg() in Animal
static void printMsg(){
^
attempting to assign weaker access privileges; was public
1 error

3. What is wrong with the below program ?     
class Animal{
 static void printMsg(){
  System.out.println("I am the super class static method");
 }
}

class Tiger extends Animal{
 static void printMsg()throws Exception{
  System.out.println("I am the sub class static method");
 }
} 

The hiding method cannot throw any exceptions that are not thrown by the overridden method.

When you tries to compile the above program compiler throws the below error.

Tiger.java:2: error: printMsg() in Tiger cannot override printMsg() in Animal
static void printMsg()throws Exception{
^
overridden method does not throw Exception
1 error

4. Can I specify weaker access specifier to the overriding method in the sub class ?
No



Covariant Return types                                                 Polymorphism Usage                                                 Home

Wednesday, 19 February 2014

Overriding Methods

A subclass has the same instance method signature like the super class instance method is called overriding.

Example
class Animal{
 void print(){
  System.out.println("I am animal");
 }
}

class Tiger extends Animal{
 void print(){
  System.out.println("I am Tiger");
 }
}

As you observe, the classes Animal and Tiger has the same method signature print(). So print method in the class Tiger overrides the method in the class Animal.

Dynamic Method Dispatch
It is a mechanism, where a call to the overridden method is resolved at run time. It is also called as run time polymorphism.

Take the same examples Animal and Tiger.
class DynamicMethodDispatchEx{
 public static void main(String args[]){
  Animal anim1 = new Tiger();
  anim1.print();
 }
}

Output
I am Tiger

As you see the statement
     Animal anim1 = new Tiger();

An object of the Tiger class is assigned to the Animal reference variable. This is completely correct in Java. We can assign a subclass object to super class reference variable.

When the program calls the print(), then at run time JVM checks, the actual object pointed by the reference variable and calls the respective method of the actual object. So it calls the print method in the Tiger class.

Modifiers
The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a default instance method in the superclass can be made public, protected, default, but not private, in the subclass.

Some points to Remember
1. Is run time polymorphism applicable to static methods also ?
No, static methods can't be overridden, they just hide the static method of the super class.

2. Is the instance variables overridden ?
No
class Animal{
 String str = "Animal";
 void print(){
  System.out.println("I am animal");
 }
}

class Tiger extends Animal{
 String str = "Tiger";
 void print(){
  System.out.println("I am Tiger");
 }
}
    
class DynamicMethodDispatchEx{
 public static void main(String args[]){
  Animal anim1 = new Tiger();
  anim1.print();
  System.out.println(anim1.str);
 }
}
   
Output
I am Tiger
Animal

If the instance variables are overridden, then the output should print the message “Tiger”. I.e, instance variables are just hide the instance variables of super class, these can't be overridden.

3. Can I apply static modifier to the subclass overriding method?
No, compiler throws an error.
 
 Example       
class Animal{
 String str = "Animal";
 
 void print(){
 System.out.println("I am animal");
 }
}

class Tiger extends Animal{
 String str = "Tiger";
 
 static void print(){
  System.out.println("I am Tiger");
 }
}
   
When tries to compile the Tiger class, below error thrown.

Tiger.java:3: error: print() in Tiger cannot override print() in Animal
static void print(){
^
overriding method is static
1 error

4. What is wrong with the below program ?    
class Animal{
 String str = "Animal";
 
 void print(){
  System.out.println("I am animal");
 }
}

class Tiger extends Animal{
 String str = "Tiger";
 
 private void print(){
  System.out.println("I am Tiger");
 }
}


When you tries to compile the above program, compiler throws the “Weaker access specifier error”

Tiger.java:3: error: print() in Tiger cannot override print() in Animal
private void print(){
^
attempting to assign weaker access privileges; was package
1 error

The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a default instance method in the superclass can be made public, protected, default, but not private, in the subclass.

5. What is the difference between static binding and Dynamic binding ?
Static binding occurs at compile time, where as Dynamic binding at run time. Dynamic method dispatch is an example for Dynamic binding.

6. What is wrong with the below program ?
class Animal{
 String str = "Animal";
 
 void print(){
  System.out.println("I am animal");
 }
}
  
class Tiger extends Animal{
 String str = "Tiger";

 void print()throws Exception{
  System.out.println("I am Tiger");
 }
}

The overriding method cannot throw any exceptions that are not thrown by the overridden method.

When you tries to compile the above program compiler throws the below error.

Tiger.java:3: error: print() in Tiger cannot override print() in Animal
void print()throws Exception{
^
overridden method does not throw Exception
1 error

7. Is the constructors inherited ?
A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses.

8. When a subclass object assigned to super class reference variable, then the reference variable can call the methods which are defined in the super class, trying to call the methods which are not defined in super class cause the compile time error.

Example
class Animal{
 void print()throws Exception{
  System.out.println("I am animal");
 }
}

class Tiger extends Animal{
 void print(){
  System.out.println("I am Tiger");
 }

 void show(){
  System.out.println("I am show method");
 }
}

class DynamicMethodDispatchEx{
 public static void main(String args[]){
  Animal anim1 = new Tiger();
  anim1.show();
 }
}
    
When you are trying to compile the program, below error thrown, since the reference variable of class Animal, “anim1” trying to call the method “show: which is not defined in the class “Animal”.

DynamicMethodDispatchEx.java:5: error: cannot find symbol
anim1.show();
^
symbol: method show()
location: variable anim1 of type Animal
1 error

9. Can I specify weaker access specifier to the overriding method in the sub class ?
No


Multi path inheritance                                                 Covariant return type                                                 Home