Scala and Java inner class

本文详细探讨了Scala中抽象类型及其在抽象类中的应用,通过实例展示了如何在类内部创建并使用内联类,以及如何解决内联类与外层类可能存在的命名冲突问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The path dependent types

 

 

 

In scala, you can have abstract types, which will be instantiated/specialized in subclasses. such as follow.

 

 

 

class Outter {
  class Inner { 
  }
}


 

and in the repl, you type

 

 

val o1 = new  Outer
val o2 = new Outer


new o1.Inner
resl1: o1.Inner = Outter$Inner@ldf6ed6
 

the resulting inner object will contain a reference to its outer object, the object references from o1.  Because the type Outer#Inner does not name any specific instance of outer, you can't create an instance of it

 

 

 

scala > new Outer#Inner
<Console> 7 : error : outer is not a legal prefix for a constructor 
             new Outer#Inner

 

 

 

so that means that in scala because the type can be an abstract member of an abstract class, Object.InnerType has a concrete type, while the static class notation, Outer.Iner may/may not have the necessary type information.

 

the Outer#Inner notation is much like the java Outer.Inner notation, let's take a close look at how the java nested class works.

 

The magic Outer.this   symbol

 

 

 

 

since it is a rule that the inner class can access the outer class's instance. but this requires a bit, since it is highly possible that the inner may have a member which has the same field as the outer class.

 

how to disambiguate the inner class and the outer class? here is an example.

 

 

 

 

 

public class InnerClassTest {
	public static void main(String[] args) {
		new OutterClass().doIt();
	}
}

class OutterClass {
	
	
	private String m_outterClassMember = null;
	
	
	public OutterClass() {
		m_outterClassMember = "Hello world";
	}
	
	public void doIt() {
		new InnerClass().sayHello();
	}
	
	
	public void enclosingClassMethod(String arg) {
		System.out.println(arg);
	}
	
	class InnerClass {
		
		public void sayHello() {
			OutterClass.this.enclosingClassMethod(OutterClass.this.m_outterClassMember);
		}
	}
}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值