Total Pageviews

Wednesday, April 11, 2012

http://www.javabeginner.com/learn-java/java-constructors

A java constructor has the same name as the name of the class to which it belongs. Constructor’s syntax does not include a return type, since constructors never return a value.
Constructors may include parameters of various types. When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition.
Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.
The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.


Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor).


public class Cube1 {

 int length;
 int breadth;
 int height;
 public int getVolume() {
  return (length * breadth * height);
 }
 Cube1() {
  length = 10;
  breadth = 10;
  height = 10;
 }
 Cube1(int l, int b, int h) {
  length = l;
  breadth = b;
  height = h;
 }
 public static void main(String[] args) {
  Cube1 cubeObj1, cubeObj2;
  cubeObj1 = new Cube1();
  cubeObj2 = new Cube1(10, 20, 30);
  System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
  System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume());
 }
}
 
 
 
 
An object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object encapsulates state and behavior.
An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables.
Creating variables of your class type is similar to creating variables of primitive data types, such as integer or float. Each time you create an object, a new set of instance variables comes into existence which defines the characteristics of that object. If you want to create an object of the class and have the reference variable associated with this object, you must also allocate memory for the object by using the new operator. This process is called instantiating an object or creating an object instance.
When you create a new object, you use the new operator to instantiate the object. The new operator returns the location of the object which you assign o a reference type.



Below is an example showing the creation of Cube objects by using the new operator.
public class Cube {

 int length = 10;
 int breadth = 10;
 int height = 10;
 public int getVolume() {
  return (length * breadth * height);
 }
 public static void main(String[] args) {
  Cube cubeObj; // Creates a Cube Reference
  cubeObj = new Cube(); // Creates an Object of Cube
  System.out.println("Volume of Cube is : " + cubeObj.getVolume());
 }
}
 
 
 
 
 

Method Overloading

Method overloading results when two or more methods in the same class have the same name but different parameters. Methods with the same name must differ in their types or number of parameters. This allows the compiler to match parameters and choose the correct method when a number of choices exist. Changing just the return type is not enough to overload a method, and will be a compile-time error. They must have a different signature. When no method matching the input parameters is found, the compiler attempts to convert the input parameters to types of greater precision. A match may then be found without error. At compile time, the right implementation is chosen based on the signature of the method call
Below is an example of a class demonstrating Method Overloading


public class MethodOverloadDemo {

 void sumOfParams() { // First Version
  System.out.println("No parameters");
 }
 void sumOfParams(int a) { // Second Version
  System.out.println("One parameter: " + a);
 }
 int sumOfParams(int a, int b) { // Third Version
  System.out.println("Two parameters: " + a + " , " + b);
  return a + b;
 }
 double sumOfParams(double a, double b) { // Fourth Version
  System.out.println("Two double parameters: " + a + " , " + b);
  return a + b;
 }
 public static void main(String args[]) {
  MethodOverloadDemo moDemo = new MethodOverloadDemo();
  int intResult;
  double doubleResult;
  moDemo.sumOfParams();
  System.out.println();
  moDemo.sumOfParams(2);
  System.out.println();
  intResult = moDemo.sumOfParams(10, 20);
  System.out.println("Sum is  " + intResult);
  System.out.println();
  doubleResult = moDemo.sumOfParams(1.1, 2.2);
  System.out.println("Sum is  " + doubleResult);
  System.out.println();
 }
} 



JAVA INHERITANCE

Java Inheritance defines an is-a relationship between a superclass and its subclasses. This means that an object of a subclass can be used wherever an object of the superclass can be used. Class Inheritance in java mechanism is used to build new classes from existing classes. The inheritance relationship is transitive: if class x extends class y, then a class z, which extends class x, will also inherit from class y.
For example a car class can inherit some properties from a General vehicle class. Here we find that the base class is the vehicle class and the subclass is the more specific car class. A subclass must use the extends clause to derive from a super class which must be written in the header of the subclass definition. The subclass inherits members of the superclass and hence promotes code reuse. The subclass itself can add its own new behavior and properties. The java.lang.Object class is always at the top of any Class inheritance hierarchy.


class Box {

 double width;
 double height;
 double depth;
 Box() {
 }
 Box(double w, double h, double d) {
  width = w;
  height = h;
  depth = d;
 }
 void getVolume() {
  System.out.println("Volume is : " + width * height * depth);
 }
}

public class MatchBox extends Box {

 double weight;
 MatchBox() {
 }
 MatchBox(double w, double h, double d, double m) {
  super(w, h, d);
  weight = m;
 }
 public static void main(String args[]) {
  MatchBox mb1 = new MatchBox(10, 10, 10, 10);
  mb1.getVolume();
  System.out.println("width of MatchBox 1 is " + mb1.width);
  System.out.println("height of MatchBox 1 is " + mb1.height);
  System.out.println("depth of MatchBox 1 is " + mb1.depth);
  System.out.println("weight of MatchBox 1 is " + mb1.weight);
 }
}
 
 
OUTPUT
 
Volume is :   1000.0

width of MatchBox 1 is 10.0

height of MatchBox 1 is 10.0

depth   of MatchBox 1 is 10.0

weight of MatchBox 1 is 10.0
 
 
==================================================================================
 

this and super keywords

The two keywords, this and super to help you explicitly name the field or method that you want. Using this and super you have full control on whether to call a method or field present in the same class or to call from the immediate superclass. This keyword is used as a reference to the current object which is an instance of the current class. The keyword super also references the current object, but as an instance of the current class’s super class.
The this reference to the current object is useful in situations where a local variable hides, or shadows, a field with the same name. If a method needs to pass the current object to another method, it can do so using the this reference. Note that the this reference cannot be used in a static context, as static code is not executed in the context of any object.


class Counter {

 int i = 0;
 Counter increment() {
  i++;
  return this;
 }
 void print() {
  System.out.println("i = " + i);
 }
}

public class CounterDemo extends Counter {

 public static void main(String[] args) {
  Counter x = new Counter();
  x.increment().increment().increment().print();
 }
}
 
 
Output
Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0


=========================================================================

Abstract Class in java

Java Abstract classes are used to declare common characteristics of subclasses. An abstract class cannot be instantiated. It can only be used as a superclass for other classes that extend the abstract class. Abstract classes are declared with the abstract keyword. Abstract classes are used to provide a template or design for concrete subclasses down the inheritance tree.
Like any other class, an abstract class can contain fields that describe the characteristics and methods that describe the actions that a class can perform. An abstract class can include methods that contain no implementation. These are called abstract methods. The abstract method declaration must then end with a semicolon rather than a block. If a class has any abstract methods, whether declared or inherited, the entire class must be declared abstract. Abstract methods are used to provide a template for the classes that inherit the abstract methods.

Abstract classes cannot be instantiated; they must be subclassed, and actual implementations must be provided for the abstract methods. Any implementation specified can, of course, be overridden by additional subclasses. An object must have an implementation for all of its methods. You need to create a subclass that provides an implementation for the abstract method.
A class abstract Vehicle might be specified as abstract to represent the general abstraction of a vehicle, as creating instances of the class would not be meaningful.


abstract class Vehicle {

 int numofGears;
 String color;
 abstract boolean hasDiskBrake();
 abstract int getNoofGears();
}


Example of a shape class as an abstract class
 
 
abstract class Shape {

 public String color;
 public Shape() {
 }
 public void setColor(String c) {
  color = c;
 }
 public String getColor() {
  return color;
 }
 abstract public double area();
}
 
 
====================================================================================
  
Java Method Overriding 
 
Method Overriding is achieved when a subclass overrides non-static methods defined in the superclass, following which the new method implementation in the subclass that is executed.
The new method definition must have the same method signature (i.e., method name and parameters) and return type. Only parameter types and return type are chosen as criteria for matching method signature. So if a subclass has its method parameters as final it doesn’t really matter for method overriding scenarios as it still holds true. The new method definition cannot narrow the accessibility of the method, but it can widen it. The new method definition can only specify all or none, or a subset of the exception classes (including their subclasses) specified in the throws clause of the overridden method in the super class
A program to explain the different concepts of Java Method Overridding


class CustomException extends Exception {

}

class SuperClassWithDifferentMethods {

 protected int field1 = 10;
 protected static int field2 = 20;
 public void method1() {
  System.out.println("SuperClassWithDifferentMethods.method1()");
 }
 public final void method2() {
  System.out.println("SuperClassWithDifferentMethods.method2()");
 }
 private void method3() {
  System.out.println("SuperClassWithDifferentMethods.method3()");
 }
 private final void method4() {
  System.out.println("SuperClassWithDifferentMethods.method4()");
 }
 public static void method5() {
  System.out.println("SuperClassWithDifferentMethods.method5()");
 }
 public void method6() throws Exception {
  System.out.println("SuperClassWithDifferentMethods.method6()");
 }
 private void method7() {
  System.out.println("SuperClassWithDifferentMethods.method7()");
 }
 private void method8(int x) {
  System.out.println("SuperClassWithDifferentMethods.method8()");
 }
 public static void method9() {
  System.out.println("SuperClassWithDifferentMethods.method9()");
 }
}

class OverridingClass extends SuperClassWithDifferentMethods {

 public int field1 = 30;
 public static int field2 = 40;
 public void method1() {
  System.out.println("OverridingClass.method1()");
 }
 //We can't override a public final method
 /*   public final void method2(){  

  System.out.println("OverridingClass.method2()");

  }*/
 private void method3() {
  System.out.println("OverridingClass.method3()");
 }
 private final void method4() {
  System.out.println("OverridingClass.method4()");
 }
 public static void method5() {
  System.out.println("OverridingClass.method5()");
 }
 public void method6() throws CustomException {
  System.out.println("OverridingClass.method6()");
 }
 public void method7() {
  System.out.println("OverridingClass.method7()");
 }
 public void method8(final int x) {
  System.out.println("OverridingClass.method8()");
 }
 //A static method cannot be overridden to be non-static instance method
 /*public void method9() {

  System.out.println("OverridingClass.method9()");

  }*/
}

public class MethodOverridingDemo {

 public static void main(String[] args) {
  OverridingClass oc1 = new OverridingClass();
  SuperClassWithDifferentMethods sc3 = new OverridingClass();
  oc1.method1();
  oc1.method2();
  //     Since its private, the below 2 methods are not visible
  /*     oc1.method3();

   oc1.method4();*/
  oc1.method5();
  try {
   oc1.method6();
  } catch (CustomException e) {
   e.printStackTrace();
  }
  oc1.method7();
  oc1.method8(100);
  System.out.println("oc1.field1 : " + oc1.field1);
  System.out.println("oc1.field2 : " + oc1.field2);
  System.out.println("sc3.field1 : " + sc3.field1);
  System.out.println("sc3.field2 : " + sc3.field2);
  sc3.method5();
  OverridingClass overClass = new OverridingClass();
 SuperClassWithDifferentMethods supClass = (SuperClassWithDifferentMethods) overClass;
  supClass.method5();
  supClass.method1();
 }
}
 
 
OUTPUT
 
OverridingClass.method1()

SuperClassWithDifferentMethods.method2()

OverridingClass.method5()

OverridingClass.method6()

OverridingClass.method7()

OverridingClass.method8()

oc1.field1   : 30

oc1.field2 : 40

sc3.field1 : 10

sc3.field2 :   20

SuperClassWithDifferentMethods.method5()

SuperClassWithDifferentMethods.method5()

OverridingClass.method1() 

No comments:

Post a Comment