Synchronized override method

We can synchronized the overridden method in subclass. See the below example.

class ShowTest {
 
    void display(int num) {
        System.out.println("Number = " + num);
    }
 
 }
 
class Test extends ShowTest
{
    synchronized void display(int num) {
        for(int i=1;i<=10;i++){
           System.out.println(num*i);  
           try{  
        	 Thread.sleep(600);  
           }catch(Exception e){
        	 System.out.println(e);
           }  
        }    
    }
 
}
class MyThread1 extends Thread{  
    ShowTest show;  
    MyThread1(ShowTest show){  
    	this.show=show;  
    }  
    public void run(){ 
    	show.display(2);  
    }        
}  
 
class MyThread2 extends Thread{  
	ShowTest show;  
	MyThread2(ShowTest show){  
		this.show=show;  
	}  
	public void run(){  
		show.display(5);  
	}  
}  
 
public class Main {  
    public static void main(String args[]){
    	Test obj = new Test();  
 
    	//creating threads.
	    MyThread1 t1=new MyThread1(obj);  
	    MyThread2 t2=new MyThread2(obj);  
 
	    //start threads.
	    t1.start();  
	    t2.start();  
    }  
}

Output

2
4
6
8
10
12
14
16
18
20
5
10
15
20
25
30
35
40
45
50

Note: It not depends on whether the super class method is synchronized or not. It will work for below case also in which super class method is synchronized.

class ShowTest {
 
    synchronized void display(int num) {
        System.out.println("Number = " + num);
    }
 
 }

Java interview questions on method overloading and overriding

Please follow and like us:
Content Protection by DMCA.com