Topics

6/recent/ticker-posts

Syntax for declaring for method in java

Syntax for declaring for method in java 




 method declaration syntax:

void add() {

}

public abstract double divide(int i, int j) throws Arithemtic Exception;

public final int add(int a, int b) {

return a + b;

}

<access_specifier> <access_modifier> return_type method_name(<paramtype1 paramname1, paramtype2 paraname2>) <throws ExceptionsList> {

}


access specifiers:

private: private methods can be accessible only within the class

default: default methods can be accessible only within the package

protected: protected methods can be accessible up to sub class outside the package. Sub class outside the package when overriding super class method, same access specifier can be maintained or access scope can be increased, but scope should not be reduced.

For example protected method can be overridden as protected/public but not default/private. If do so compilation error comes saying "Weaker Access Specifier Error".

public: public methods can be accessible anywhere.


Example on protected member/method access in sub classes outside the package:

package a;

public class A {

protected void a() {}

}


package b;

class B extends A {

protected void a() {}

}


package b;

class C extends B {

public void a() {}

}

package b;

class D {

B b=new B();

b.a();

}


package c;

classs E extends A {

public void a() {}

}


package c;

classs F  {

B b=new B();

b.a(); // error

E e=new E();

e.a();

}

access modifiers:

  • abstract:

* method which is declared but not implemented is declared as abstract

* no method implementation/no flower braces exist for abstract method

* class which contains abstract method must also be declared as abstract

* But abstract class need not contain abstract methods

* Abstract methods must be implemented in sub classes

* Abstraction importance is to achieve runtime polymorphism

  • final:

Methods which don't want to be overridden in sub classes are declared as final.

If all the methods of a class want to be declared as final, instead of declaring all the methods as final, declare class itself as final. When there is no inheritance there is no overriding.

For better memory optimization it is recommended to declare final methods as static also.

But not all static methods are final.

  • static:

static methods will have only one copy of memory. non-static methods will have instance methods. static methods are called as class methods. non-static methods are called as class instance methods.

native: 

synchronized: Threads

Example on abstract class with abstract method:

// EmpPayroll.java

public class EmpPayroll {

  public void calSal();

}

// AdminEmpPayroll.java

public class AdminEmpPayroll extends EmpPayroll {

  public void calSal() {

    System.out.println("Admin Emp Payroll is : now*pds");

  }

}

// SalesEmpPayroll.java

public class SalesEmpPayroll extends EmpPayroll {

  public void calSal() {

    System.out.println("Sales Emp Payroll is : (now*pds)+(salesamt*perc)");

  }

}

// ProdEmpPayroll.java

public class ProdEmpPayroll extends EmpPayroll {

  public void calSal() {

    System.out.println("Prod Emp Payroll is : (now*pds)+(overtimehours*othamt)");

  }

}

// EPFactory.java

public class EPFactory {

  public static EmpPayroll getEmpPayroll(String type) {

    if(type.equalsIgnoreCase("admin"))

  return new AdminEmpPayroll();

    else if(type.equalsIgnoreCase("sales"))

  return new SalesEmpPayroll();

    else

  return new ProdEmpPayroll();

  }

}

// EPClient.java

public class EPClient {

  public static void main(String rags[]) {

    EmpPayroll ep=EPFactory.getEmpPayroll(rags[0]);

ep.calSal();

  }

}


  • Abstraction main benefit is to loosely couple client with the various versions of method implementation they want to invoke. Runtime binding / Runtime Polymorphism.

  • In the above client program the client holding EmpPayroll class ref may be assigned/initialized with any one of the sub class of EmpPayroll class at runtime. Based on the runtime argument passed into factory method getEmpPayroll() of EPFactory one of the EmpPayroll class object will be created and returned.


// FinalSuperClass.java

public class FinalSuperClass {

  // final int MAX_AGE;

  // final static int MAX_AGE=18;

  final static int MAX_AGE;

  /* variable MAX_AGE might not have been initialized */

  public FinalSuperClass() {

    // MAX_AGE=21;

  }

  static {

    MAX_AGE=21;

  }

}


// FinalSuperClass.java

public class FinalSuperClass {

  // 1st way

  final int MAX_AGE=18;

  /* variable MAX_AGE might not have been initialized */

  public FinalSuperClass() {

    // MAX_AGE=21; // cannot reinitialize

  }

  

  // 2nd way

  final int MAX_AGE;

  public FinalSuperClass() {

    MAX_AGE=21;

  }


}


// FinalSuperClassSubClass.java

public class FinalSuperClassSubClass extends FinalSuperClass {

  public FinalSuperClassSubClass() {

    MAX_AGE=23;//NA

  }

}


In how many ways we can call static variable of a class.

// StaticVaraibleTester.java

public class StaticVaraibleTester {


  static double MAX_AMT=10000.00;

  double depositAmt;

  

  public static void aStaticMethod() {

  System.out.println(MAX_AMT); // A

  // System.out.println(depositAmt); // NA

  System.out.println(FinalSuperClass.MAX_AGE); 

  System.out.println(new FinalSuperClass().MAX_AGE); 


  System.out.println(FinalSuperClassSubClass.MAX_AGE); 

  System.out.println(new FinalSuperClassSubClass().MAX_AGE); 

  }

  

  public void aNonStaticMethod() {

  System.out.println(FinalSuperClass.MAX_AGE); 

  System.out.println(new FinalSuperClass().MAX_AGE); 


  System.out.println(FinalSuperClassSubClass.MAX_AGE); 

  System.out.println(new FinalSuperClassSubClass().MAX_AGE);     

  }

}


Note: 

  • final variables can be initialized at the time of declaration. 
  • They can also be initialized constructor.
  • But cannot reinitialized in the same class methods are sub class constructors also.
  • If variable is declared as static and final then it can be initialized at the time of declaration or can be initialized in the static blocks, but not in the static methods.
  • If variable is static alone then it can be initialized in initialized during declaration, static blocks and can be reinitialized any number of times static methods.
  • static variables can be accessed used super class name, sub class name, super class object reference and sub class object reference.


/*

ChromeOptions options=new ChromeOptions();

IWebDriver driver=new ChromeDriver(options);

var browser=new InteractiveBrowser(driver);

browser.

*/


Example on static and non-static blocks:

class A {

A() {}

v m1() {}

p s v main(String rags[]) {}

static {

}

static {

}

}


A a;


static block:

    static blocks will be executed at the time of class loading.

non-static blocks are also called as constructor blocks which will execute before constructor execution. constructor is used while creating object of the class.


class E {

  static {

    System.out.println("first static block of E");

  }

  

  E() {

  }

  

  static {

    System.out.println("second static block of E");

  }

}


class F {

  E e;

  public static void main(String rags[]) {

   E e=new E();

  }

}


// StaticExample.java

public class StaticExample {


  static {

    System.out.println("This is first static block");

  }

  

  public StaticExample() {

    System.out.println("This is StaticExample class constructor");

  }

  

  public static String staticString="Static variable";

  

  static {

    System.out.println("This is second static block "+staticString);

  }

  

  public static void main(String rags[])  {

    StaticExample se=new  StaticExample();

StaticExample.staticMethod2();

  }

  

  static {

     staticMethod1();

System.out.println("This is third static block");

  }

  

  public static void staticMethod1() {  

System.out.println("This is staticMethod1()");

  }

  

  public static void staticMethod2() {  

System.out.println("This is staticMethod2()");

  }

}

output: 

This is first static block

This is second static block Static Variable

This is staticMethod1()

This is third static block

This is StaticExample class constructor

This is staticMethod2()

Note: static blocks are mainly used to load native libraries into java program. Native libraries files contains functions implemented in C++/VC++. We can connect them through native methods declared in Java class.

Questions:

At what level non-static/instance variables are declared, initialized and used ? 

declared at class level, initialized at constructor level and used in non-static methods.

At what level static/class variables are declared, initialized and used?

declared at class level, initialized at static block level and used in both static and non-static methods.


class NativeDemo {

native void printOnPrinter(String message);

// native method implementation exist in .dll file

static {

System.loadLibrary("HPDeskJet1020.dll");

}

}


class NativeDemoClient {

p s v main(String rags[]) {

NativeDemo nd=new NativeDemo();

nd.printOnPrinter("Hello Ram");

}

}

Non-static blocks:

  • Non-static blocks are also called as Constructor blocks. 

// ConstructorBlockExample.java

public class ConstructorBlockExample {


   // non-static blocks / constructor blocks are open and closed with flower braces without static keyword.


   {

System.out.println("This is first constructor block");

   }


   public ConstructorBlockExample() {

System.out.println("public no parameter constructor called");

   }

   

   public ConstructorBlockExample(String param1) {

System.out.println("public single String parameter constructor called");

   }


   public ConstructorBlockExample(String param1, String param2) {

System.out.println("public two String parameter constructor called");

   }

   

   {

System.out.println("This is second constructor block");

   }

   

   public static void main(String rags[]) {

      ConstructorBlockExample cbe=new ConstructorBlockExample();

      ConstructorBlockExample cbe=new ConstructorBlockExample("Argument1");

      ConstructorBlockExample cbe=new ConstructorBlockExample("Argument1", "Argument2");

   }   

}


javac ConstructorBlockExample.java

During class compilation, compiler will copy all non-static block statements into every constructor before constructor written statements.


java ConstructorBlockExample

  • This is first constructor block
  • This is second constructor block
  • public no parameter constructor called

  • This is first constructor block
  • This is second constructor block
  • public single String parameter constructor called

  • This is first constructor block
  • This is second constructor block
  • public two String parameter constructor called



Why constructor blocks? What will be written in constructor blocks?

  • Statements which are repeatedly written in every constructor are written in constructor block so that the code will become reusable. The code written in the constructor block is copied into every constructor before constructor written statements during compilation time.


Post a Comment

0 Comments