Non-virtual Methods in Java - java tutorials

Ads
 

Non-virtual Methods in Java - java tutorials

non virtual methods in java

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

Ads

Ads