Showing posts with label Inheritance. Show all posts
Showing posts with label Inheritance. Show all posts

The object class in java Programming

Monday, 12 November 2012
There is one special class object defined by java , All other classes are subclasses of object ,That is object is a superclass of all other classes .This means that a reference variable type object can refer to an object of any other class .Also since array are implemented as classes a variable of type object can also refer to any array

Object defines the following a method ,which means that they are available in every object


Method
Purpose
Object clone() creates a new object that is the same as the object cloned
boolean euals(Object obj) Determines whether one object is equal to another
void finalize() called before an unused object is recyled
Class getClass() Obtains the class of an object at run time
int hashCode() Returns the hash code associated with the invoking object
void notify() Resumes execution of a thread waiting on the invoking object
void notifyAll() This method wakes up all threads that are waiting on this object's monitor.
String toString() This method returns a string representation of the object.
void wait() This method causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
void wait(long timeout) This method causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
void wait(long timeout, int nanos) This method causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

Example of Final variable, Final method and Class in Java


Final in java is very important keyword and can be applied to class, method, and variables in Java. In this java final tutorial we will see what is final keyword in Java, what does it mean by making final variable, final method and final class in java and what are primary benefits of using final keywords in Java and finally some examples of final in Java. Final is often used along with static keyword in Java to make static final constant and you will see how final in Java can increase performance of Java application.


Final keyword in java can also be applied to methods. A java method with final keyword is called final method and it can not be overridden in sub-class. You should make a method final in java if you think it’s complete and its behavior should remain constant in sub-classes. Final methods are faster than non-final methods because they are not required to be resolved during run-time and they are bonded on compile time.

Benefits of final keyword in Java

Here are few benefits or advantage of using final keyword in Java:


1. Final keyword can be applied to member variable, local variable, method or class in Java.

2. Final member variable must be initialized at the time of declaration or inside constructor, failure to do so will result in compilation error.

3. You can not reassign value to final variable in Java.

4. Local final variable must be initializing during declaration. 

5. Only final variable is accessible inside anonymous class in Java.

6. Final method can not be overridden in Java.

7. Final class can not be inheritable in Java.

8. Final is different than finally keyword which is used on Exception handling in Java.

9. Final should not be confused with finalize() method which is declared in object class and called before an object is garbage collected by JVM.

10.All variable declared inside java interface are implicitly final.

11.Final and abstract are two opposite keyword and a final class can not be abstract in java.

12 Final methods are bonded during compile time also called static binding.

13.Final variables which is not initialized during declaration are called blank final variable and must be initialized on all constructor either explicitly or by calling this(). Failure to do so compiler will complain as "final variable (name) might not be initialized".

14. Making a class, method or variable final in Java helps to improve performance because JVM gets an opportunity to make assumption and optimization.

15. As per Java code convention final variables are treated as constant and written in all Caps

16.Final keyword improves performance. Not just JVM can cache final variable but also application can cache frequently use final variables.

17. Final variables are safe to share in multi-threading environment without additional synchronization overhead.

18. Final keyword allows JVM to optimized method, variable or class.

Final keyword declaration


 final int hoursInDay=24;



Program : FinalExample.java

public class FinalExample {

        public static void main(String[] args) {
             
                /*
                 * Final variables can be declared using final keyword.
                 * Once created and initialized, its value can not be changed.
                 */
                final int hoursInDay=24;
             
                //This statement will not compile. Value can't be changed.
                //hoursInDay=12;
             
                System.out.println("Hours in 5 days = " + hoursInDay * 5);
             
        }
}
Output 



G:\>javac FinalExample.java
G:\>java FinalExample
Hours in 5 days = 120


Example of Final variable, Final method and Class in Java

Abstract Class Example in Java Program

Java Abstract classes are used to declare common characteristics of subclasses. An abstract class cannot be instantiated. It can only be used as a super class 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.

You can require that certain methods be overridden by subclasses by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the superclass. Thus, a subclass must override them—it cannot simply use the version defined in the superclass. To declare an abstract method, use this general form:

abstract type name(parameter-list);

 As you can see, no method body is present. Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. There can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated with the new operator. Such objects would be useless, because an abstract class is not fully defined. Also, you cannot declare abstract constructors, or abstract static methods. Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be itself declared abstract. Here is a simple example of a class with an abstract method, followed by a class which implements that method:

Program AbstractDemo.java

abstract class Shape
{
 abstract void draw();
}
class Rectangle extends Shape
  {
   void draw()
    {
     System.out.println("Drawing Rectangle");
    }
  }

class Traingle extends Shape
  {
   void draw()
    {
     System.out.println("Drawing Traingle");
    }
  }

class AbstractDemo
 {
  public static void main(String args[])
   {
    Shape s1=new Rectangle();
    s1.draw();
    s1=new Traingle();
    s1.draw();
   }
 }
Output 


G:\>javac AbstractDemo.java
G:\>java AbstractDemo
Drawing Rectangle
Drawing Traingle 



Abstract Class Example in Java Program

The subclass must define an implementation for every abstract method of the abstract superclass, or the subclass itself will also be abstract. Similarly other shape objects can be created using the generic Shape Abstract class.
A big Disadvantage of using abstract classes is not able to use multiple inheritance. In the sense, when a class extends an abstract class, it can’t extend any other class.

Method Overriding in Java

In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its super class, then the method in the subclass is said to override the method in the super class. When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the super class will be hidden.

Rules for method overriding:

  • The argument list should be exactly the same as that of the overridden method.
  • The return type should be the same or a subtype of the return type declared in the original overridden method in the super class.
  • The access level cannot be more restrictive than the overridden method's access level. For example: if the super class method is declared public then the overridding method in the sub class cannot be either private or public. However the access level can be less restrictive than the overridden method's access level.
  • Instance methods can be overridden only if they are inherited by the subclass.
  • A method declared final cannot be overridden.
  • A method declared static cannot be overridden but can be re-declared.
  • If a method cannot be inherited then it cannot be overridden.
  • A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.
  • A subclass in a different package can only override the non-final methods declared public or protected.
  • An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.
  • Constructors cannot be overridden.

Program Override.java

class A
 {
  int i, j;
  A(int a, int b)
   {
    i = a;
    j = b;
   }
  void show()
   {
    System.out.println("i and j: " + i + " " + j);
   }
 }

// Create a subclass by extending class A.


class B extends A
 {
    int k;
    B(int a, int b, int c)
     {
      super(a, b);
      k = c;
     }
// overload show()

    void show(String msg)
     {
      System.out.println(msg + k);
     }
 }

class Override
 {
   public static void main(String args[])
    {
     B subOb = new B(10, 20, 30);
     subOb.show("This is k: ");

// this calls show() in B

     subOb.show();

// this calls show() in A
    }
}


Here, super.show( ) calls the superclass version of show( ). Method overriding occurs only when the names and the type signatures of the two methods are identical. If they are not, then the two methods are simply overloaded


Output 

G:\>javac Override.java
G:\>java Override
This is k: 3
i and j: 1 2

Method Overriding in Java


Multilevel Hierarchy in java programming

In simple inheritance a subclass or derived class derives the properties from its parent class, but in multilevel inheritance a subclass is derived from a derived class. One class inherits only single class. Therefore, in multilevel inheritance, every time ladder increases by one. The lower most class will have the properties of all the super classes’.

It is common that a class is derived from another derived class.The class student serves as a base class for the derived class marks, which in turn serves as a base class for the derived class percentage.The class marks is known as intermediates base class since it provides a link for the inheritance between student and percentage.
The chain is known as inheritance path. When this type of situation occurs, each subclass inherits all of the features found in all of its super classes. In this case, percentage inherits all aspects of marks and student. 
To understand the flow of program read all comments of program.


Program : Multi_Inhe.java

class student
{
    int rollno;
    String name;

    student(int r, String n)
    {
        rollno = r;
        name = n;
    }
    void dispdatas()
    {
        System.out.println("Rollno = " + rollno);
        System.out.println("Name = " + name);
    }
}

class marks extends student
{
    int total;
    marks(int r, String n, int t)
    {
        super(r,n);   //call super class (student) constructor
        total = t;
    }
    void dispdatam()
    {
        dispdatas();    // call dispdatap of student class
        System.out.println("Total = " + total);
    }
}

class percentage extends marks
{
    int per;
    
    percentage(int r, String n, int t, int p)
    {
        super(r,n,t);  //call super class(marks) constructor
        per = p;
    }
    void dispdatap()
    {
        dispdatam();    // call dispdatap of marks class
        System.out.println("Percentage = " + per);
    }
}
class Multi_Inhe
{
    public static void main(String args[])
    {
        percentage stu = new percentage(102689, "VINEETH", 350, 70); //call constructor percentage
        stu.dispdatap();  // call dispdatap of percentage class
    }
}
Output 
G:\>javac Multi_Inhe.java
G:\>java Multi_Inhe
Rollno = 102689
Name = VINEETH
Total = 350
Percentage = 70

Multilevel Hierarchy in java programming

Use of super keyword in java


The super keyword acts some what like this ,except that it always that it always refers to the super class of the subclass in which it is used.This usage has the following general form

super.member

member can be either a method or an instance variable.  the super keyword is most applicable to situations in which memebe names of a subclass hide memebers by the same name in the superclass .Consider this simple class hierarchy


class Base
{
  int i;
}
class SubClass extends Base
 {
  int i; // this i hides the i in A
  SubClass(int a, int b) {
    super.i = a; // i in A
    i = b; // i in B
  }
  void show()
  {
    System.out.println("i in superclass: " + super.i);
    System.out.println("i in subclass: " + i);
  }
}
public class Mainkey
{
  public static void main(String args[])
  {
    SubClass subOb = new SubClass(1, 2);
    subOb.show();
  }
}
Output 

G:\>javac Mainkey.java
G:\>java Mainkey
i in superclass: 1
i in subclass: 2

Use of super keyword in java

Using super to Call Superclass Constructors

A subclass can call a constructor method defined by its superclass by use of the following form of super

super(parameter-list);

  • parameter-list is defined by the constructor in the super class.
  • super(parameter-list) must be the first statement executed inside a subclass' constructor. 
Program Mainsuper.java


class Box {
  private double width;
  private double height;
  private double depth;

  Box(Box ob) { // pass object to constructor
    width = ob.width;
    height = ob.height;
    depth = ob.depth;
  }
  Box(double w, double h, double d) {
    width = w;
    height = h;
    depth = d;
  }
  double volume() {
    return width * height * depth;
  }
}
class BoxWeight extends Box {
  double weight; // weight of box
  BoxWeight(Box ob) { // pass object to constructor
    super(ob);
  }
}
public class Mainsuper
 {
  public static void main(String args[]) {
    Box mybox1 = new Box(20, 30, 25);
    BoxWeight myclone = new BoxWeight(mybox1);
    double vol;

    vol = mybox1.volume();
    System.out.println("Volume of mybox1 is " + vol);
  }
}

Here,BoxWeight() calls super() with the parametrized w,h and d .This causes the Box() constructor to be called ,Which initialize Width ,height,depth using these values.BoxWeight no longer initializes these values itself.if only needs to initilize the value unique to it weight .This leaves Box free to make these values private if desired . In the preceding example super() wa called with three arguments .since constructors can be overloaded ,super() can be called using any form defined by the super class.The constructor executed will be the one that matches the arguments.For example ,here is a complete implementation of BoxWeight that provides constructors for the various ways that a box can be constructed .In each case super() is called using the appropriate arguments .


Output 

G:\>javac Mainsuper.java
G:\>java Mainsuper
Volume of mybox1 is 15000.0


Using super to Call Superclass Constructors

Inheritance Basics-Java Programming

 Inheritance is a major component of object-oriented programming. Inheritance will allow you to define a very general class, and then later define more specialized classes by simply adding some new details to the older more general class definition. This saves work, because the more specialized class inherits all the properties of the general class and you, the programmer, need only program the new features.

For example, you might define a class for vehicles that has instance variables to record the vehicle's number of wheels and maximum number of occupants. You might then define a class for automobiles, and let the automobile class inherit all the instance variables and methods of the class for vehicles. The class for automobiles would have added instance variables for such things as the amount of fuel in the fuel tank and the license plate number, and would also have some added methods. (Some vehicles, such as a horse and wagon, have no fuel tank and normally no license plate, but an automobile is a vehicle that has these "added" items.) You would have to describe the added instance variables and added methods, but if you use Java's inheritance mechanism, you would get the instance variables and methods from the vehicle class automatically.


To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword. To see how, let's begin with a short example. The following program creates a superclass called A and a subclass called B. Notice how the keyword extends is used to create a subclass of A.

Program

 class A
 {
  int i, j;
  void showij()
   {
    System.out.println("i and j: " + i + " " + j);
   }
 }


class B extends A
 {
   int k;
   void showk()
    {
      System.out.println("k: " + k);
    }
   void sum()
    {
      System.out.println("i+j+k: " + (i+j+k));
    }
 }

class SimpleInheritance
 {
   public static void main(String args[])
     {
       A superOb = new A();
       B subOb = new B();

       superOb.i = 10;
       superOb.j = 20;
       System.out.println("Contents of superOb: ");
       superOb.showij();
       System.out.println();
/* The subclass has access to all public members of
its superclass. */

       subOb.i = 7;
       subOb.j = 8;
       subOb.k = 9;
       System.out.println("Contents of subOb: ");
       subOb.showij();
       subOb.showk();
       System.out.println();
       System.out.println("Sum of i, j and k in subOb:");
       subOb.sum();
     }
}
Output 


G:\>javac SimpleInheritance.java

G:\>java SimpleInheritance
Contents of superOb:
i and j: 10 20

Contents of subOb:
i and j: 7 8
k: 9

Sum of i, j and k in subOb:
i+j+k: 24


Inheritance Basics-Java Programming
 

learn java programming Copyright © 2011-2012 | Powered by appsackel.org