Create a package accesstest1 and accesstest2 under com.grazitti and create four classes on your own to explain the default, public, private and protected access specifiers

0

Assignment: Module 04

Create a package accesstest1 and accesstest2 under com.grazitti and create four classes on your own to explain the default, public, private and protected access specifiers
Assignment: Module 04

Create a package accesstest1 and accesstest2 under com.grazitti and create four classes on your own to explain the default, public, private and protected access specifiers

Here is an example of how you could create two packages, accesstest1 and accesstest2, under the package com.grazitti in Java and add four classes to explain the default, public, private, and protected access specifiers:



package com.grazitti.accesstest1;

class DefaultClass {
    int defaultVar;

    void defaultMethod() {
        System.out.println("This is a default access method.");
    }
}

public class PublicClass {
    public int publicVar;

    public void publicMethod() {
        System.out.println("This is a public access method.");
    }
}

class AccessTest1 {
    public static void main(String[] args) {
        DefaultClass dc = new DefaultClass();
        dc.defaultMethod();

        PublicClass pc = new PublicClass();
        pc.publicMethod();
    }
}   


package com.grazitti.accesstest2;

class PrivateClass {
    private int privateVar;

    private void privateMethod() {
        System.out.println("This is a private access method.");
    }
}

class ProtectedClass {
    protected int protectedVar;

    protected void protectedMethod() {
        System.out.println("This is a protected access method.");
    }
}

class AccessTest2 {
    public static void main(String[] args) {
        PrivateClass pc = new PrivateClass();
        // pc.privateMethod(); // Cannot be accessed outside the class

        ProtectedClass prc = new ProtectedClass();
        prc.protectedMethod();
    }
}   

This example demonstrates how you can use the default, public, private, and protected access specifiers in Java. The default access specifier means that the class, variable, or method can be accessed within the same package. The public access specifier means that the class, variable, or method can be accessed from anywhere. The private access specifier means that the class, variable, or method can only be accessed within the same class. The protected access specifier means that the class, variable, or method can be accessed within the same package and in subclasses of the class.


👉Java Fundamentals Module 03 - Part 03👈

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
✨ Updates