Java程序创建包访问外部类和同包成员
顾名思义, Java中的一个包包含所有具有相同功能的相同类型的类、抽象类、接口等。单个包可以包含许多类,抽象类,例如Java.util 包等。
有两种类型的包:
- 内置包:这些是在Java jar 文件中预定义的包。 Java最常用的包。 UTIL和Java.IO在Java包。
- 自定义包:这些包由用户创建,用于存储相关类,为特定任务定义的一些其他实用程序、接口和抽象类等称为用户自定义包。
项目结构:
Project -- GFG
|
|
Package 1 GFG1
|
GFG1.java (class)
Package 2 GFG2
|
GFG2.java (class)
|
GFG3.java (class)
套餐一:
GFG1。Java
Java
package GFG1;
// Creating Interface
interface GFG1Interface {
String name = "This is the Interface of GF1";
void GFG1Interface();
}
public class GFG1 {
// Instance variable
String name;
// Getter Function
public String getName() { return name; }
// Setter Function
public void setName(String name) { this.name = name; }
}
Java
package GFG2;
// Creating Interface
interface GFG3Interface {
String name = "GFG";
public void interfaceGFG();
}
// Creating Abstract class
abstract class GFGabstract {
String name = "GFGAbstract";
// Abstract Method
abstract public void print();
}
public class GFG3 {
// Instance Variables
int first;
int second;
// Creating Constructor
GFG3(int a, int b)
{
this.first = a;
this.second = b;
}
// Creating add Function
public int add() { return this.first + this.second; }
}
Java
package GFG2;
// Importing the members of GFG1 package
import GFG1.*;
public class GFG2 implements GFG3Interface {
@Override public void interfaceGFG()
{
System.out.println(
"This is the interface of the GFG3class");
}
public static void main(String args[])
{
// Creating object of class GFG1
GFG1 ob = new GFG1();
// Calling setName Function
ob.setName("GFGsetter");
System.out.println(ob.getName());
// Creating object of class GFG2
GFG2 ob2 = new GFG2();
ob2.interfaceGFG();
}
}
套餐二:
GFG3。Java
Java
package GFG2;
// Creating Interface
interface GFG3Interface {
String name = "GFG";
public void interfaceGFG();
}
// Creating Abstract class
abstract class GFGabstract {
String name = "GFGAbstract";
// Abstract Method
abstract public void print();
}
public class GFG3 {
// Instance Variables
int first;
int second;
// Creating Constructor
GFG3(int a, int b)
{
this.first = a;
this.second = b;
}
// Creating add Function
public int add() { return this.first + this.second; }
}
访问包2类中包1类的成员:
GFG2。Java
Java
package GFG2;
// Importing the members of GFG1 package
import GFG1.*;
public class GFG2 implements GFG3Interface {
@Override public void interfaceGFG()
{
System.out.println(
"This is the interface of the GFG3class");
}
public static void main(String args[])
{
// Creating object of class GFG1
GFG1 ob = new GFG1();
// Calling setName Function
ob.setName("GFGsetter");
System.out.println(ob.getName());
// Creating object of class GFG2
GFG2 ob2 = new GFG2();
ob2.interfaceGFG();
}
}
输出: