黑马程序员----[20150428][面向对象5]

本文深入探讨Java中内部类、静态内部类、匿名内部类、异常处理等面向对象高级特性,通过实例代码解析每种类型的特点及应用场景,旨在帮助开发者理解和掌握Java面向对象编程的精髓。

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

------   Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

第五讲  面向对象5

1.内部类访问规则

将一个类定义在另一个类的里面,对里面那个类就称为 内部类(内置类,嵌套类)。

访问特点:
• 内部类可以直接访问外部类中的成员,包括私有成员。
之所以可以直接访问外部类中的成员,是因为内部类中持有了一个外部类的引用,格式 外部类名.this
• 而外部类要访问内部类中的成员必须要建立内部类的对象。
class Outer{
	private int x = 3;
	
	class Inner }            //内部类在外部类中的成员中
		//int x = 4;
		void function(){
			//int x = 6;
			System.out.println("innner :"+Outer.this.x);//this.x会输出4.直接写x,也就省略了Outer.this。
		}
	}

	void method(){
		Inner in = new Inner();
		in.function();
	}
}

class  InnerClassDemo{
	public static void main(String[] args) {
		Outer out = new Outer();
		out.method();
		//直接访问内部类中的成员。
<span style="white-space:pre">		</span>//Outer.Inner in = new Outer().new Inner();
<span style="white-space:pre">		</span>//in.function();
	}
}

2.静态内部类

访问格式:
1,当内部类定义在外部类的成员位置上,而且非私有,可以在外部其他类中,可以直接建立内部类对象。
格式
外部类名.内部类名  变量名 = 外部类对象.内部类对象;
Outer.Inner in = new Outer().new Inner();


2,当内部类在成员位置上,就可以被成员修饰符所修饰。
       比如,private:将内部类在外部类中进行封装。
static:内部类就具备static的特性。
当内部类被static修饰后,只能直接访问外部类中的static成员。出现了访问局限

在外部其他类中,如何直接访问static内部类的非静态成员呢?
new Outer.Inner().function();

在外部其他类中,如何直接访问static内部类的静态成员呢?
Outer.Inner.function();

注意:当内部类中定义了静态成员,该内部类必须是static的。
    当外部类中的静态方法访问内部类时,内部类也必须是static的。

3.内部类定义原则

当描述事物时,事物的内部还有事物,该事物用内部类来描述。
因为内部事务在使用外部事物的内容。(一般用在程序设计上)
class Body{
	private class XinZang
	{
	}

	public void show(){
		new XinZang().
	}	
}

4.匿名内部类

/*
内部类定义在局部时,
1,不可以被成员修饰符修饰
2,可以直接访问外部类中的成员,因为还持有外部类中的引用。
但是不可以访问它所在的局部中的变量。只能访问被final修饰的局部变量。
*/
class Outer
{
	int x = 3;
	void method(final int a)            //内部类访问只能是final修饰
	{
		final int y = 4;            //这里的局部变量,若想被内部类访问也得是final修饰
		class Inner
		{
			void function()
			{
				System.out.println(y);
			}
		}
	
		new Inner().function();         //在内部类后边new	
	}
}

class  InnerClassDemo3
{
	public static void main(String[] args) 
	{
		Outer out = new Outer();
		out.method(7);               //进栈,赋给a,被锁住了,再出栈。语句结束
		out.method(8);               //重新进栈,赋值,锁住,再出栈。语句结束。
	}

}
匿名内部类:
1,匿名内部类其实就是内部类的简写格式。
2,定义匿名内部类的前提:
内部类必须是继承一个类或者实现接口。
3,匿名内部类的格式:  new 父类或者接口(){定义子类的内容}
4,其实匿名内部类就是一个匿名子类对象。而且这个对象有点胖。 可以理解为带内容的对象。
5,匿名内部类中定义的方法最好不要超过3个。

原始的代码(没用内部类的时候):
class Outer
{
	int x = 3;

	class Inner 
	{
		void method()
		{
			System.out.println("method :"+x);
		}
		
	}

	public void function()
	{

		new Inner().method();

	}
}

class InnerClassDemo4 
{
	public static void main(String[] args) 
	{
		new Outer().function();
	}
}
内部类必须是继承一个类或者实现接口。
abstract class AbsDemo
{
	abstract void show();	
}

class Outer
{
	int x = 3;

	class Inner extends AbsDemo    //第一步
	{
		void show()            //第二步
		{
			System.out.println("show :"+x);
		}
	}

	public void function()
	{
                new Inner().show();  //第三步+第四步
	}
}

class InnerClassDemo4 
{
	public static void main(String[] args) 
	{
		new Outer().function();
	}
}
匿名内部类就是对内部类的一个简化,也就是简化上面的代码:
分析内部类做了什么事情:第一步内部类继承了一个类,第二步进行了方法覆写,第三部创建了对象,第四步调用方法。
匿名内部类就是把上边的四步融合成一步来完成。没有名字,就不能用new对象,那就用(new父类)来实现子类代码。
abstract class AbsDemo
{
	abstract void show();
	
}

class Outer
{
	int x = 3;

	/*
	class Inner extends AbsDemo
	{
		void show()
		{
			System.out.println("show :"+x);
		}
	}
	*/

	public void function()
	{
               //new Inner().show();
	
                new AbsDemo()             //这就是匿名内部类,这个对象是AbsDemo子类对象,只不过是用父类来实现
		{
			void show()
			{
				System.out.println("x==="+x);
			}
		}.show();                //就是把上边的Inner()给替换了。
	}
}

class InnerClassDemo4 
{
	public static void main(String[] args) 
	{
		new Outer().function();
	}
}
内部类的局限性:(调用自己的方法不行)
abstract class AbsDemo
{
	abstract void show();	
}

class Outer
{
	int x = 3;

	public void function()
	{
		//AbsDemo a = new Inner();
//		Inner in = new Inner();
//		in.show();
//		in.abc();
	
		AbsDemo d = new AbsDemo()
		{
			int num = 9;
			void show()
			{
				System.out.println("num==="+num);
			}
			void abc()
			{
				System.out.println("haha");
			}
		};

		d.show();
		//d.abc();      //编译失败;因为父类中没定义过

	}
}

class InnerClassDemo4 
{
	public static void main(String[] args) 
	{
		new Outer().function();
	}
}
说白了,匿名内部类就是简化书写,覆写方法。
下面是小练习:(匿名之前)
interface Inter
{
	void method();
}

class Test 
{
	//补足代码。通过匿名内部类。
	static class Inner implements Inter
	{
		public void method()
		{
			System.out.println("method run");
		}
	}

	static Inter function()
	{
		return new Inter();
	}
}

class InnerClassTest 
{
	public static void main(String[] args) 
	{
		Test.function().method();
	}
}
匿名之后:
interface Inter
{
	void method();
}

class Test 
{
	//补足代码。通过匿名内部类。
	/*
	static class Inner implements Inter
	{
		public void method()
		{
			System.out.println("method run");
		}
	}
	*/

	static Inter function()
	{
		return new Inter()           //这里就是匿名内部类
		{
			public void method()
			{
				System.out.println("method run");
			}
		};
	}
}

class InnerClassTest 
{
	public static void main(String[] args) 
	{
		//Test.function():Test类中有一个静态的方法function。
		//.method():function这个方法运算后的结果是一个对象。而且是一个Inter类型的对象。
		//因为只有是Inter类型的对象,才可以调用method方法。

		Test.function().method();	
         }
}

5.异常概述

异常:就是程序在运行时出现不正常情况。
异常由来:问题也是现实生活中一个具体的事物,也可以通过java的类的形式进行描述。并封装成对象。
其实就是java对不正常情况进行描述后的对象体现。

对于问题的划分:两种:一种是严重的问题,一种非严重的问题。

对于严重的,java通过Error类进行描述。
对于Error一般不编写针对性的代码对其进行处理。

对与非严重的,java通过Exception类进行描述。
对于Exception可以使用针对性的处理方式进行处理。

无论Error或者Exception都具有一些共性内容。
比如:不正常情况的信息,引发原因等。

Throwable
|--Error
|--Exception

6.异常try-catch

2,异常的处理
java 提供了特有的语句进行处理。
try
{
	需要被检测的代码;
}
catch(异常类 变量)
{
	处理异常的代码;(处理方式)
}
finally
{
	一定会执行的语句;
}
例如:
class Demo
{
	int div(int a,int b)
	{
		return a/b;
	}
}

class  ExceptionDemo
{
	public static void main(String[] args) 
	{
		Demo d = new Demo();
		try
		{
			int x = d.div(4,0);
			System.out.println("x="+x);
		}
		catch (Exception e)
		{
			System.out.println("除零啦");
		}		
		
		System.out.println("over");
	}
}
3,对捕获到的异常对象进行常见方法操作。
String getMessage():获取异常信息。

class Demo
{
	int div(int a,int b)
	{
		return a/b;
	}
}

class  ExceptionDemo
{
	public static void main(String[] args) 
	{
		Demo d = new Demo();
		try
		{
			int x = d.div(4,0);
			System.out.println("x="+x);
		}
		catch (Exception e)           //Exception e = new ArithmeticException();
		{
			System.out.println("除零啦");
			System.out.println(e.getMessage());//  / by zero;
			System.out.println(e.toString());// 异常名称 : 异常信息。

			e.printStackTrace();//异常名称,异常信息,异常出现的位置。
							//其实jvm默认的异常处理机制,就是在调用printStackTrace方法。
							//打印异常的堆栈的跟踪信息。
		}			
		System.out.println("over");
	}
}

7.异常声明throws

在函数上声明异常。便于提高安全性,让调用出进行处理。不处理编译失败。

  当函数功能是别人编写的,你在调用的时候,你根本不知道是不是要try-catch处理,因为你不知道这个功能会不会发生问题。这就造成一个问题,当你传参数的时候有可能程序停掉。
这时编写功能的时候,你知道会发生异常,那就要在函数上加上标识throws,当别人使用的时候我这功能有可能出现问题,希望他处理一下。
class Demo
{
	int div(int a,int b)throws Exception//在功能上通过throws的关键字声明了该功能有可能会出现问题。
	{
		return a/b;
	}
}
如果在调用的时候调用者没处理,那就会发生异常报告。通常处理异常有两种方式:1,对其进行捕捉。2,声明抛出
例如在main中抛出,抛给虚拟机处理:
public static void main(String[] args) throws Exception
当编译的时候是不会出现问题的,但是当调用的时候如果出现异常,虚拟机会用默认的方式处理,程序立即结束。不会运行到最后。

8.多异常处理

当编写功能的时候,有可能出现多个异常,你声明的越具体,那么处理的就可以更具体。

对多异常的处理。
1,声明异常时,建议声明更为具体的异常。这样处理的可以更具体。
2,对方声明几个异常,就对应有几个catch块。不要定义多余的catch块。
如果多个catch块中的异常出现继承关系,父类异常catch块放在最下面。

建立在进行catch处理时,catch中一定要定义具体处理方式。
不要简单定义一句 e.printStackTrace(),也不要简单的就书写一条输出语句。
class Demo
{
	int div(int a,int b)throws ArithmeticException,ArrayIndexOutOfBoundsException//在功能上通过throws的关键字声明了该功能有可能会出现问题。
	{
		int[] arr = new int[a];
		System.out.println(arr[4]);
		return a/b;
	}
}

class  ExceptionDemo2
{
	public static void main(String[] args) //throws Exception
	{
		Demo d = new Demo();
		try
		{
			int x = d.div(5,0);
			System.out.println("x="+x);
		}	
		catch (ArithmeticException e)
		{
			System.out.println(e.toString());
			System.out.println("被零除了!!");
		}
		catch (ArrayIndexOutOfBoundsException e)
		{
			System.out.println(e.toString());
			System.out.println("角标越界啦!!");
		}
		catch(Exception e)
		{
			System.out.println("hahah:"+e.toString());
		}	
		System.out.println("over");
	}
}

9.自定义异常

因为项目中会出现特有的问题,而这些问题并未被java所描述并封装对象。
所以对于这些特有的问题可以按照java的对问题封装的思想,将特有的问题,进行自定义的异常封装。

需求:在本程序中,对于除数是-1,也视为是错误的是无法进行运算的。
那么就需要对这个问题进行自定义的描述。
class FuShuException extends Exception
{
}

class Demo
{
	int div(int a,int b)throws FuShuException
	{
		if(b<0)
			throw new FuShuException();//手动通过throw关键字抛出一个自定义异常对象。

		return a/b;
	}
}

class  ExceptionDemo3
{
	public static void main(String[] args) 
	{
		Demo d = new Demo();
		try
		{
			int x = d.div(4,-9);
			System.out.println("x="+x);		
		}
		catch (FuShuException e)
		{
			System.out.print(e.toString());
			System.out.print("除数出现负数了");
		}			
		System.out.print("over");
	}
}
这里编译运行之后会输出,FuShuException  除数出现负数了 over
当在函数内部出现了throw抛出异常对象,那么就必须要给对应的处理动作。
要么在内部try catch处理。
要么在函数上声明让调用者处理。

一般情况在,函数内出现异常,函数上需要声明。

发现打印的结果中只有异常的名称,却没有异常的信息。
因为自定义的异常并未定义信息。

如何定义异常信息呢?
因为父类中已经把异常信息的操作都完成了。
所以子类只要在构造时,将异常信息传递给父类通过super语句。
那么就可以直接通过getMessage方法获取自定义的异常信息。

class FuShuException extends Exception 
{
	private String message;
	FuShuException(String message)
	{
		this.message = message;
	}

	public String getMessage()
	{
		return message;
	}

}

class Demo
{
	int div(int a,int b)throws FuShuException
	{
		if(b<0)
			throw new FuShuException("出现了除数是负数的情况");//手动通过throw关键字抛出一个自定义异常对象。
		return a/b;
	}
}

class  ExceptionDemo3
{
	public static void main(String[] args) 
	{
		Demo d = new Demo();
		try
		{
			int x = d.div(4,-9);
			System.out.println("x="+x);		
		}
		catch (FuShuException e)
		{
			System.out.println(e.toString());             //此方法会自动调用getMessage()方法
			System.out.println("除数出现负数了");
		}
				
		System.out.println("over");

	}
}

最终的版本是这样的:
class FuShuException extends Exception //getMessage();
{
	private int value;

	FuShuException()
	{
		super();
	}
	FuShuException(String msg,int value)
	{
		super(msg);
		this.value = value;
	}
	public int getValue()
	{
		return value;
	}
}

class Demo
{
	int div(int a,int b)throws FuShuException
	{
		if(b<0)
			throw new FuShuException("出现了除数是负数的情况------ / by fushu",b);//手动通过throw关键字抛出一个自定义异常对象。
		return a/b;
	}
}

class  ExceptionDemo3
{
	public static void main(String[] args) 
	{
		Demo d = new Demo();
		try
		{
			int x = d.div(4,-9);
			System.out.println("x="+x);		
		}
		catch (FuShuException e)
		{
			System.out.println(e.toString());
			//System.out.println("除数出现负数了");
			System.out.println("错误的负数是:"+e.getValue());
		}
		System.out.println("over");

	}
}
自定义异常:
必须是自定义类继承Exception。

继承Exception原因:
异常体系有一个特点:因为异常类和异常对象都被抛出。
他们都具备可抛性。这个可抛性是Throwable这个体系中独有特点。
只有这个体系中的类和对象才可以被throws和throw操作。

10.throw和throws的区别

throws和throw的区别
throws使用在函数上。
throw使用在函数内。

throws后面跟的异常类。可以跟多个。用逗号隔开。
throw后跟的是异常对象。

11.RuntimeException

Exceptoin中有一个特殊的子类异常RuntimeException 运行时异常。

如果在函数内容抛出该异常,函数上可以不用声明,编译一样通过。
如果在函数上声明了该异常。调用者可以不用进行处理。编译一样通过;


之所以不用在函数声明,是因为不需要让调用者处理。
当该异常发生,希望程序停止。因为在运行时,出现了无法继续运算的情况,希望停止程序后,对代码进行修正。

自定义异常时:如果该异常的发生,无法在继续进行运算,就让自定义异常继承RuntimeException。

对于异常分两种:
1,编译时被检测的异常。
2,编译时不被检测的异常(运行时异常。RuntimeException以及其子类)

class FuShuException extends RuntimeException
{
	FuShuException(String msg)
	{
		super(msg);
	}
}
class Demo
{
	int div(int a,int b)throws Exception//throws ArithmeticException
	{
		
		if(b<0)
			throw new Exception("出现了除数为负数了");
		if(b==0)
			throw new ArithmeticException("被零除啦");
		return a/b;
	}
}

class ExceptionDemo4 
{
	public static void main(String[] args) 
	{
		
		Demo d = new Demo();
		
		int x = d.div(4,-9);
		System.out.println("x="+x);		
		
		System.out.println("over");
	}
}

12.异常练习

/*
毕老师用电脑上课。

开始思考上课中出现的问题。


比如问题是
	电脑蓝屏。
	电脑冒烟。

要对问题进行描述,封装成对象。


可是当冒烟发生后,出现讲课进度无法继续。

出现了讲师的问题:课时计划无法完成。

*/

class LanPingException extends Exception
{
	LanPingException(String message)
	{
		super(message);
	}
}

class MaoYanException extends Exception
{
	MaoYanException(String message)
	{
		super(message);
	}
}

class NoPlanException extends Exception
{
	NoPlanException(String msg)
	{
		super(msg);
	}
}

class Computer
{
	private int state = 3;
	public void run()throws LanPingException,MaoYanException
	{
		if(state==2)
			throw new LanPingException("蓝屏了");
		if(state==3)
			throw new MaoYanException("冒烟了");

		System.out.println("电脑运行");
	}
	public void reset()
	{
		state = 1;
		System.out.println("电脑重启");		
	}
}

class Teacher
{
	private String name;
	private Computer cmpt;

	Teacher(String name)
	{
		this.name = name;
		cmpt = new Computer();
	}

	public void prelect()throws NoPlanException
	{
		try
		{
			cmpt.run();			
		}
		catch (LanPingException e)
		{
			cmpt.reset();
		}
		catch (MaoYanException e)
		{
			
			test();
			throw new NoPlanException("课时无法继续"+e.getMessage());
			
		}
		System.out.println("讲课");
	}
	public void test()
	{
		System.out.println("练习");
	}

}

class ExceptionTest 
{
	public static void main(String[] args) 
	{
		Teacher t = new Teacher("毕老师");
		try
		{
			t.prelect();
		}
		catch (NoPlanException e)
		{
			System.out.println(e.toString());
			System.out.println("换老师或者放假");
		}	
	}
}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值