简体   繁体   中英

Default members of an public class

I am learning core java from NPTEL courses in that course during the lecture about access specifier they had told us that "When a class is public all its members with default access specifier are also public". But I had tried to call the default method of a public class from the class of another package. But it was giving a compile-time error is this concept wrong???

package week4;

public class TestClass2 {

   void msg() {

        System.out.println("Hi I am in class ");

    }

    public static void main(String[] args) {

        TestClass2 obj=new TestClass2();

        obj.msg();}
}

//2nd class code 
 
package week3;

import week4.*;

public class TestClass1 {

     public static void main(String[] args) {

     TestClass2 obj=new TestClass2();

        obj.msg();//compile Time error (msg() from week4 is not visible)

    }

}

When a class is public all its members with default access specifier are also public

This is wrong.

Actual concept of default access modifier --> It is called package-private ie all members are visible within the same package but are not accessible from other packages.

So to access the msg() method from TestClass2 in TestClass1 , you have to declare the method as public void msg() .

It is default/accessible to the classes within the same package. Try accessing the same msg() method from a class inside the package week4 and you should be able to.

When we start coding in Java, we were told there is ONLY ONE MAIN METHOD, I see that you are putting it into both classes, plus if you want to share the "vibes" from methods among themselves, you gotta use at least public void msg(); And depending on the funtionality, using a return(); should be a must.

Plus, you should know the concept of the "static methods", this means that you will be able to use the properties from other methods, in this case, to your main method

Look at this example:

//- - - - EXAMPLE BEGINNING - - - - //- - - - - method class - - - - - -

package week4;

public class TestClass2 {

public static void msg() {

    System.out.println("Hi I am in class ");

    }
}

//- - - - main class - - - - -

package week3;

import week4.*;

public class TestClass1 {

   static TestClass2 testit = new TestClass2();


 public static void main(String[] args) {
    TestClass1 myobject= new TestClass1();
    myobject.testit.msg();
    
}
 
}

//- - - - END OF THE EXAMPLE - - - - -

/ Hope it was useful, remember, static is very important when it comes to manage data from methods /

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM