[英]Test1 & Test2 in the same package, so why do I need import test2? if I don't use import, Inn inn1 = test2.new Inn(4), It will go wrong
Test1和Test2在同一软件包中,为什么我需要导入test2?
如果我不使用import,Inn inn1 = test2.new Inn(4),它将出错。 &&其他问题:
public void show(final int number){
}
如果我在这里使用final,这是什么意思?
package info;
import info.Test2.Inn;
public class Test1 {
public static void main(String[] args) {
int sum = 1;
Test2 test2 = new Test2(2);
Test2.Inn inn = test2.new Inn(3);
Inn inn1 = test2.new Inn(4);
for (int i = 0; i < 9; i++){
sum = (sum + 1) * 2;
}
System.out.println(sum);
}
}
class Test2 {
private int test;
public Test2(int test) {
this.test = test;
}
class Inn{
private int inn;
public Inn(int inn) {
this.inn = inn;
}
}
}
同一软件包只能省略软件包名称。
整个签名:
package_name.Test2.Inn
package_name.Test2
->
Test2.Inn
Test2
如果使用Inn
代替Test2.Inn
如果在同一包中有一个名为Inn
怎么办?
该final
在方法签名装置number
不能被修改。
因此,方法中不允许使用number++
类的东西。
您可以按以下方式删除导入语句
Test2.Inn inn1 = test2.new Inn(4);
因此,整个代码可能看起来像
public class Test1 {
public static void main(String[] args) {
int sum = 1;
Test2 test2 = new Test2(2);
Test2.Inn inn = test2.new Inn(3);
Test2.Inn inn1 = test2.new Inn(4);
for (int i = 0; i < 9; i++){
sum = (sum + 1) * 2;
}
System.out.println(sum);
}
}
class Test2 {
private int test;
public Test2(int test) {
this.test = test;
}
class Inn{
private int inn;
public Inn(int inn) {
this.inn = inn;
}
}
}
我再给你看看
使Test2内部类成为Test1类
public class Test1 {
public static void main(String[] args) {
int sum = 1;
Test2 test2 = new Test2(2);
Test2.Inn inn = test2.new Inn(3);
Test2.Inn inn1 = test2.new Inn(4);
for (int i = 0; i < 9; i++){
sum = (sum + 1) * 2;
}
System.out.println(sum);
}
class Test2 {
private int test;
public Test2(int test) {
this.test = test;
}
class Inn{
private int inn;
public Inn(int inn) {
this.inn = inn;
}
}
}
}
但是代码尚未编译,因为您无法在Test1类的静态方法中访问Test2类。
所以,你可以这样做
静态类Test2
现在,您可以通过声明Test2.Inn来访问Test1的静态成员Test2类及其内部类Inn。
public class Test1 {
public static void main(String[] args) {
int sum = 1;
Test2 test2 = new Test2(2);
Test2.Inn inn = test2.new Inn(3);
Test2.Inn inn1 = test2.new Inn(4);
for (int i = 0; i < 9; i++){
sum = (sum + 1) * 2;
}
System.out.println(sum);
}
static class Test2 {
private int test;
public Test2(int test) {
this.test = test;
}
class Inn{
private int inn;
public Inn(int inn) {
this.inn = inn;
}
}
}
}
然后,上面的代码有点难看,所以我终于可以编写自己的代码
import Test1.Test2.Inn;
public class Test1 {
public static void main(String[] args) {
int sum = 1;
Test2 test2 = new Test2(2);
Inn inn = new Inn(3);
Inn inn1 = new Inn(4);
for (int i = 0; i < 9; i++){
sum = (sum + 1) * 2;
}
System.out.println(sum);
}
static class Test2 {
private int test;
public Test2(int test) {
this.test = test;
}
static class Inn{
private int inn;
public Inn(int inn) {
this.inn = inn;
}
}
}
}
我认为这全都与类的范围或可访问性有关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.