Scenario #5:


Expected Understanding: Interface, access modifiers, Method Overriding

1) Create a package called tamilnadu.chennai
2) Create an interface ‘TrafficRules’ under this package
3) Make sure this interface is public interface
– Add variable String trafficCommisssioner = “Kavin”;
– Add below methods
– void goByDieselVehicle();
– void goByBicycle();

package tamilnadu.chennai;
public interface TrafficRules
{
 String trafficCommissioner = "Kavin";
 public void goByDieselVehicle();
 public void goByBicycle();
 
 }

4) Create class called ‘CommonManInChennai’ with main method in the same package tamilnadu.chennai
– Implement interface ‘TrafficRulesChennai’
– Create instance for this class and access all the methods

package tamilnadu.chennai;
public class CommonManinChennai implements TrafficRules
{
public static void main(String[] args)
{

CommonManinChennai cm = new CommonManinChennai();
cm.goByDieselVehicle();
cm.goByBicycle();
}

 public void goByDieselVehicle()
 {
 System.out.println("Car");
 }
 public void goByBicycle()
 {
  System.out.println("Cycling");
 }
 }

5) Now, create another package called ‘india.newDelhi’
6) Create an interface ‘TrafficRulesDelhi’ under this package
7) Make sure this interface is not public interface – it should be default interface
– Add variable String trafficCommisssioner = “Navin”;
– Add below methods
– void dontGoByDieselVehicle();
– void goByBicycle();

package india.newDelhi;
interface TrafficRulesDelhi
{
String trafficCommissioner = "Naveen";
public void dontGoByDieselVehicle();
 public void goByBicycle();

}

8) Create class called ‘CommonManInDelhi’ with main method in the same package india.newDelhi
– Implement interface ‘TrafficRulesDelhi’
– Create instance for this class and access all the methods
– Now, implement interface ‘TrafficRulesChennai’ also.
– Add unimplemented methods
– Access all the methods and observe the difference.

package india.newDelhi;
import tamilnadu.chennai.TrafficRules;
class CommonManinDelhi implements TrafficRulesDelhi,TrafficRules
{

public static void main(String[] args)
{
CommonManinDelhi cd = new CommonManinDelhi();
cd.dontGoByDieselVehicle();
cd.goByBicycle();

}
public void dontGoByDieselVehicle()
{
 System.out.println("Don't Go");
 
}
 public void goByBicycle()
{
System.out.println("Go");
}

 public void goByDieselVehicle()
 {
 System.out.println("Go by vehicle");
 }
/* public void goByBicycle()       // method already declared
 {
    System.out.println("Go by bicycle");
 }*/

}

Output

After the Error (GoByBicycle() method already declared so remove that method)

Leave a Reply

Create your own website, free on WordPress.com.Create your own website.
Start free