AIM: Write an application that illustrates method overriding in the same package and different packages. Also demonstrate accessibility rules in inside and outside packages.
1. Method Overriding
A.class
B.class
Example.class
Output (Compile A, B, and Example file and run only Example class like following)
2. Accessibility rules in inside and outside packages
2.1 Accessibility rules in inside packages
Protection.java
Example.java
Output (compile Protection and Example java file and run only Example class like following)
2.1 Accessibility rules in outside packages
1. Method Overriding
A.class
class A { void show() { System.out.println("Inside Class-A"); } }
B.class
class A { void show() { System.out.println("Inside Class-A"); } }class B extends A { //Overriding method show of class A void show() { System.out.println("Inside Class-B"); } }
Example.class
public class Example { public static void main(String arg[]) { B obj=new B(); obj.show(); //show() method of class-B will called. } }
Output (Compile A, B, and Example file and run only Example class like following)
Method Overriding in package in java by practical server |
2. Accessibility rules in inside and outside packages
2.1 Accessibility rules in inside packages
Protection.java
public class Protection { int n=1; public int n_pub=2; }
Example.java
public class Example { public static void main(String arg[]) { Protection p1=new Protection(); System.out.println("n= "+p1.n); System.out.println("n_pub= "+p1.n_pub); } }
Output (compile Protection and Example java file and run only Example class like following)
Accessibility rules in inside packages in java by practical server |
2.1 Accessibility rules in outside packages
Protection.java
package p1; public class Protection { int n=1; public int n_pub=2; }
Example.java
import p1.Protection; public class Example { public static void main(String arg[]) { Protection p1=new Protection(); System.out.println("n= "+p1.n); // this line generate error without it, output
//like following System.out.println("n_pub= "+p1.n_pub); } }
Output
Blue line shows without System.out.println("n= "+p1.n); line. so comment this line for proper output
Red line shows error with System.out.println("n= "+p1.n);
Blue line shows without System.out.println("n= "+p1.n); line. so comment this line for proper output
Red line shows error with System.out.println("n= "+p1.n);
Accessibility rules in outside packages in java by practical server |
Happy Coding :)
1 Comments
Thank you ji🙏
ReplyDeletePost a Comment