non virtual methods in java
Ads
TutorialsLets see the concept of virtual methods, a virtual function is function whose behavior can not be overridden by inheriting the class.
In C++ programming you can make a function virtual , that tell the compiler that you want to use the most derived methods in object hierarchy.
In Java programming language all the methods are virtual, i.e. the most derived method is always called. Consider an example -
A.javapublic class A { public void m() { System.out.println("Class A's method m() Called"); } }
public class B extends A{ public void m(){ System.out.println("Class B's method m() Called"); } }
public class C { public static void main(String[] args) { A a = new A(); a.m(); A a1 = new B(); a1.m(); B b = new B(); b.m(); } }
When you will run the above code you will see the output as
Class A's method m() Called Class B's method m() Called Class B's method m() Called |
The better way to achieve the non-virtual function in java is that make all the non-virtual method static. Consider the example given below -
A.javapublic class A { public static void m() { System.out.println("Class A Called"); } }
public class B extends A{ public static void m(){ System.out.println("Class B Called"); } }
public class C { public static void main(String[] args) { A a = new A(); a.m(); A a1 = new B(); a1.m(); B b = new B(); b.m(); } }
Class A's method m() Called Class A's method m() Called Class B's method m() Called |
Posted on: April 18, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles
Advertisements
Ads
Ads
Discuss: Non-virtual Methods in Java - java tutorials
Post your Comment