Home Javatutorials Non-virtual Methods in Java - java tutorials
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Non-virtual Methods in Java - java tutorials

Advertisement
non virtual methods in java

Non Virtual Methods in Java

Lets 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.java
public class A {
	public void m() {
		System.out.println("Class A's method m() Called");
	}
}

B.java
public class B extends A{
	public void m(){
		System.out.println("Class B's method m() Called");
	}
}

C.java
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.java
public class A {
	public static void m() {
		System.out.println("Class A Called");
	}
}

B.java
public class B extends A{
	public static void m(){
		System.out.println("Class B Called");
	}
}

C.java
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
Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 18, 2011

Related Tutorials

Ask Questions?    Discuss: Non-virtual Methods in Java - java tutorials  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Sudharsan
April 23, 2012
Ambiguty inthe Definition

"a virtual function is function whose behavior can not be overridden by inheriting the class." this is the definition you stated, i think it is the definition for NON-Virtual function.
DMCA.com