Access Members of a Class from Another Class in Java



To access the members of a class from other class.

  • First of all, import the class.
  • Create an object of that class.
  • Using this object access, the members of that class.

Suppose there is a class in a package called myPackage with a method named display()

package myPackage;
public class Sample {
   public void display() {
      System.out.println("Hello");
   }
}

You can access it as.

import myPackage;
public class MyClass {
   public static void main(String args[]) {
      Sample s = new Sample();
      s.done();
   }
}

Output

hello
Updated on: 2019-07-30T22:30:20+05:30

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements