您的位置:首页 > 编程语言 > Java开发

java内部类之成员内部类,通过内部类实现多继承

2017-12-25 18:30 501 查看
public class MemberInnerClass {
public static void main(String[] args){
//创建外部类对象
Outer1 outer=new Outer1();
Outer1.Inner1 inner=outer.new Inner1();
inner.innerShow();
//outer.outerShow();
}
}
class Outer1{
private String name="张三";
private int num1=10;
public void outerShow(){
System.out.println(name);
System.out.println(num1);
//Inner1 inner1=new Inner1();
//inner1.innerShow();
//System.out.println(num2);//外部类不能直接访问内部类的成员。
}
public class Inner1{//内部类可以是私有的,但是不可以通过外部类的对象来获得内部类的对象
private String name="李四";
private int num2=20;
//private static int num3=30;//在成员内部类中不能声明静态成员,属性和方法。
private static final int num3=30;//静态常量在内部类中是可以的
public void innerShow(){
System.out.println(name);
System.out.println(Outer1.this.name);//内部类可以直接访问外部类的成员和方法,包括私有
System.out.println(num2);
//outerShow();//等于Outer1.this.outerShow();只是因为他们没有同名的方法,所有可以省略。
//Outer1.this.outerShow();
}
}
}


通过成员内部类实现多继承

public class MultiExtendsDemo{
public static void main(String[] args){
C c=new C();
c.showA();
c.showB();
}
}
class A{
public void showA(){
System.out.println("A");
}
}
class B{
public void showB(){
System.out.println("B");
}
}
class C {
private class A1 extends A{
public void showA(){
super.showA();
}
}
private class B1 extends B{
public void showB(){
super.showB();
}
}
public void showA(){
new A1().showA();
}
public void showB(){
new B1().showB();
}
}

实现抽象类和接口中的相同方法
public class Demo2{
public static void main(String[] args){
Son son=new Son();
son.show();
son.show2();
}
}
abstract class Parent{
public abstract void show();
}
interface IShow{
public abstract void show();
}
/*class Son extends Parent implements IShow{
public
}*/
class Son extends Parent{
public void show(){
System.out.println("抽象类中的show方法");
}
private class Inner2 implements IShow{
public void show(){
System.out.println("接口中的show方法");
}
}
public void show2(){
new Inner2().show();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐