Java基础_13多态、异常和String类

今天的内容

1.多态

2.异常

3.String类

1.多态

多种形态。

同一个事件,在不同的对象操作事件的时候,会有不同的结果!!!

需要三个条件:

​ 1.继承

​ 2.重写

​ 3.父类的引用指向子类的对象

1.1向上转型

父类的引用指向子类的对象

Person person = new Man();

向上转型案例

package com.qf.a_duotai;

abstract class Animal {
	public abstract void eat ();
}
class Dog extends Animal{
	public void eat () {
		System.out.println("狗吃大骨头");
	}
}
class Cat extends Animal{
	public void eat () {
		System.out.println("猫吃鱼");
	}
}
class Person {
	public void feed (Animal animal) {//向上转型
		animal.eat();
	}
	
}
public class Demo1 {
	public static void main(String[] args) {
		Person person = new Person();
		/**
		 * public void feed (Animal animal) {
				animal.eat();
			}
			形参是:  Animal animal
			实参是:  new Dog()
			实参赋值给形参
			Animal animal = new Dog();   父类的引用指向子类的对象
			Animal animal = new Cat();  父类的引用指向子类的对象
			向上转型
		 */
		person.feed(new Dog());
		person.feed(new Cat());
	}
}

1.2向下转型

先向上再向下转型

package com.qf.a_duotai;

abstract class Animal {
	public abstract void eat ();
}
class Dog extends Animal{
	public void eat () {
		System.out.println("狗吃大骨头");
	}
}
class Cat extends Animal{
	public void eat () {
		System.out.println("猫吃鱼");
	}
	//独有的方法
	public void sleep () {
		System.out.println("睡觉");
	}
}
class Person {
	public void feed (Animal animal) {//向上转型
		animal.eat();
		//父类的引用无法调用子类的独有 方法
		//现在我就想让你调用子类独有的方法!!!
		//只能拿当前对象调用自己独有的方法
		//Cat对象,可以将animal转为cat对象
		//语法格式:   子类  子类对象 = (子类)父类的引用
		 Cat cat = (Cat)animal;//向下转型
		 cat.sleep();
	}
	
}
public class Demo1 {
	public static void main(String[] args) {
		Person person = new Person();
		/**
		 * public void feed (Animal animal) {
				animal.eat();
			}
			形参是:  Animal animal
			实参是:  new Dog()
			实参赋值给形参
			Animal animal = new Dog();   父类的引用指向子类的对象
			Animal animal = new Cat();  父类的引用指向子类的对象
			向上转型
		 */
		//person.feed(new Dog());
		person.feed(new Cat());
	}
}

1.3instanceof关键字

instanceof是Java关键字

语法格式:

boolean ret = 对象的引用   instanceof  类的类型

主要能干嘛? 判断 这个对象的引用是不是类的类型或者子类

package com.qf.a_duotai;

class Moneky {
	
}
class People extends Moneky{
	
}
public class Demo2 {
	public static void main(String[] args) {
		People people = new People();
		//boolean ret = 对象的引用   instanceof  类的类型
		//判断 这个对象的引用是不是类的类型或者子类
		System.out.println(people instanceof People);//true
		System.out.println(people instanceof Moneky);//true
		Moneky moneky = new Moneky();
		System.out.println(moneky instanceof People);//false
		
		Moneky moneky2 = new People();
		System.out.println(moneky2 instanceof People);//true
		System.out.println(moneky2 instanceof Moneky);//true
		//总结:
		//  instanceof 的左边  是对象   平辈或者晚辈
		//intanceof的右边 是类   是平辈或者长辈
		
		
		
	}
}

package com.qf.a_duotai;

abstract class Animal {
	public abstract void eat ();
}
class Dog extends Animal{
	public void eat () {
		System.out.println("狗吃大骨头");
	}
}
class Cat extends Animal{
	public void eat () {
		System.out.println("猫吃鱼");
	}
	//独有的方法
	public void sleep () {
		System.out.println("睡觉");
	}
}
class Person {
	public void feed (Animal animal) {//向上转型
		animal.eat();
		//父类的引用无法调用子类的独有 方法
		//现在我就想让你调用子类独有的方法!!!
		//只能拿当前对象调用自己独有的方法
		//Cat对象,可以将animal转为cat对象
		//语法格式:   子类  子类对象 = (子类)父类的引用
		//person.feed(new Dog());
		//person.feed(new Cat());
		//Animal animal = new Dog();
		// animal instanceof Cat  false
		//Animal animal = new Cat();
		//animal instanceof Cat true
		
		if (animal instanceof Cat) {
			 Cat cat = (Cat)animal;//向下转型
			 cat.sleep();
		}
		
	}
	
}
public class Demo1 {
	public static void main(String[] args) {
		Person person = new Person();
		/**
		 * public void feed (Animal animal) {
				animal.eat();
			}
			形参是:  Animal animal
			实参是:  new Dog()
			实参赋值给形参
			Animal animal = new Dog();   父类的引用指向子类的对象
			Animal animal = new Cat();  父类的引用指向子类的对象
			向上转型
		 */
		person.feed(new Dog());
		person.feed(new Cat());
		
		//思路:  将子类(Dog)给父类的引用  ,然后再讲父类的引用强转为子类(Cat)
	}
}

2.异常

2.1Java中异常

程序允运行,发生不可预期的事件。它阻止了程序的正常的执行。这就是Java中异常。

Java提供了非常优秀的异常处理机制。都是封装好的。

让大家看看什么是异常。

package com.qf.b_exception;

import java.util.Arrays;

public class Demo1 {
	public static void main(String[] args) {
		int[] arr = new int[2];
		arr[0] = 89;
		arr[1] = 98;
		arr[2] = 76;
		/**
		 * ArrayIndexOutOfBoundsException: 2
	at com.qf.b_exception.Demo1.main(Demo1.java:10)
		 */
		System.out.println(Arrays.toString(arr));
		
	}
}

2.2Throwable类

Java封装好的类,咋学啊?

JDK 官方的API文档 就相当于字典一样

搜Throwable

Java 8 中文版 - 在线API中文手册 - 码工具 (matools.com)

Throwable类是Java语言中所有错误(Error)和异常(Exception)的父类。

通常使用两个子类的实例ErrorException来表示出现异常情况。 通常,这些实例是在特殊情况的上下文中新创建的,以便包括相关信息(如堆栈跟踪数据)

1.构造方法

想到 new Throwable()

Throwable()构造一个新的可抛出的 null作为其详细信息。

Throwable(String message)构造一个具有指定的详细消息的新的throwable。

2.方法

StringgetMessage()返回此throwable的详细消息字符串。
voidprintStackTrace()将此throwable和其追溯打印到标准错误流。
StringtoString()返回此可抛出的简短描述。
package com.qf.c_throwable;



public class Demo1 {
	public static void main(String[] args) {
		//	Throwable()
		//构造一个新的可抛出的 null作为其详细信息。
		Throwable throwable = new Throwable();
		System.out.println(throwable);
		//返回此throwable的详细消息字符串。
		System.out.println(throwable.getMessage());//null
//		System.err.println("嘻嘻");
		/**
		 * java.lang.Throwable
			at com.qf.c_throwable.Demo1.main(Demo1.java:9)
		将此throwable和其追溯打印到标准错误流。
		 */
		throwable.printStackTrace();
		
		System.out.println(throwable.toString());
		
		//构造一个具有指定的详细消息的新的throwable。
		Throwable throwable2 = new Throwable("单身!!!");
		System.out.println(throwable2.getMessage());//单身!!!
		throwable2.printStackTrace();
		System.out.println(throwable2.toString());
	
	}
}

以上的类是Java中专门处理Error和Exception的异常的类

开发不用,学习它的子类ErrorException

2.3错误和异常

Error: 是代表JVM本身错误,程序员是无法通过代码进行调试的。

Exception: 异常 ,写Java代码的时候发生不可预期的效果。没有达到咱们想要的结果。

可以借助于Java封装好的异常的处理机制来解决。

​ 异常分为两大类:

​ 运行时异常: 数组下标越界, 代码写上没报错,一点击运行按钮,有异常。

​ 编译时异常: 代码写上了,直接报红了。

2.4异常【重点】

Java代码的时候发生不可预期的效果。没有达到咱们想要的结果

咋办?

针对于异常有两种解决方案:

​ 1.捕捉

​ 2.抛出

2.4.1捕捉异常

程序在运行当中有可能发生异常。如果没有发生异常,不需要捕捉。发生异常需要捕捉。

捕捉异常的语法格式:

try {
	有可能出现异常的代码
} catch (异常对象) {
    
}

执行流程: 先看 try里面的代码 是否有异常,如果没有 直接跳过catch 接着执行代码。如果

有异常。里面 通过关键字catch 抓相应的异常对象。

package com.qf.d_exception;

public class Demo1 {
	public static void main(String[] args) {
		test(10, 0);
	}
	public static void test (int a, int b) {
		int ret = 0;
		try {
			ret = a / b;
			//jvm搞出来一个对象  new  ArithmeticException();
			//Exception e =  new  ArithmeticException();  多态
		} catch (Exception e) {
			//返回此throwable的详细消息字符串
			System.out.println("除数不能为0");
			System.out.println(e.getMessage());/// by zero
		}
		 
		System.out.println(ret);
		//总结:  当代码出现异常的时候,jvm会抛出一个实例对象(异常的)
		//try-catch  抓住这个异常对象,然后进行下一步的处理暂时保证代码没有报错
	}
}

package com.qf.d_exception;

public class Demo2 {
	public static void main(String[] args) {
		test(1,0, new int[2]);
	}
	public static void test (int a, int b, int[] arr) {
		int ret = 0;
		try {
			ret = a / b;//ArithmeticException
			arr[4] = 23;//ArrayIndexOutOfBoundsException: 4
		//} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
		 }catch (Exception e) {//重点是Exception  e
				System.out.println("嘻嘻");
		}
		
		
		
	}
}

package com.qf.d_exception;

public class Demo2 {
	public static void main(String[] args) {
		test(1,1, new int[2]);
	}
	public static void test (int a, int b, int[] arr) {
		int ret = 0;
		try {
			ret = a / b;//ArithmeticException
			arr[1] = 23;//ArrayIndexOutOfBoundsException: 4
		//} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
		 }catch (Exception e) {//重点是Exception  e
				System.out.println("嘻嘻");
		} finally {
			//最终地意思,无论有没有异常都要执行finally代码
			System.out.println("哈哈 无论如何我都要执行");
		}
	
	}
}

2.4.2异常抛出

咱们可以在代码的异常处,抛出一个异常。不管了,告知程序员此处有异常,你要写正确的代码

throws 异常类

在方法的小括号的后面写的

package com.qf.d_throws;

public class Demo1 {
	public static void main(String[] args) {
		test(1, 0);
	}
	public static void test (int a, int b) throws ArithmeticException{
		int ret = a / b;//运行时异常
		System.out.println(ret);
	}
	public static void test1 (int a, int b) throws InterruptedException {
		Thread.sleep(1000);
	}
	//总结:   运行时异常    即使不写 throws也能运行。调用者不知道有异常,就有可能出错。所以建议写上throws
	//     编译时异常   必须得写的不写 他就报错。报错的话他就无法运行
	//告知调用者此处有异常的抛出,写代码的时候要小心的!!!
}

扩展:

关键字throw 动词

throw  异常对象

抛出一个异常对象, 仿照jvm虚拟机抛出一个对象。自己造错!!!

package com.qf.d_throws;

public class Demo2 {
	public static void main(String[] args) {
		test(0);
	}
	public static void test (int a) throws ArithmeticException{
		if (a == 0) {
			//仿照jvm  抛出一个异常
			//自己造错
			//ArithmeticException 运行时异常
			//System.exit(0);//程序退出
			throw new ArithmeticException();
		}
		System.out.println("嘻嘻");
	}
	public static void test1 (int a) throws InterruptedException {
		if (a == 0) {
			//仿照jvm  抛出一个异常
			//自己造错
			//InterruptedException 编译时异常
			throw new InterruptedException();
		}
		System.out.println("嘻嘻");
	}
}	

throw和throws区别

throw  是抛出的动作     会自己造一个异常,你写上throw 异常对象的时候,一旦代码执行了。就会抛出一个异常。影响代码的执行!!!
throws 是抛出的名词    在方法的小括号的后面写的,告知调用者 此时这个方法中有可能有异常!!!

总结:

1.try-catch
2.throws
3.throw

3.String

String类代表字符串。 Java程序中的所有字符串文字(例如"abc" )都被实现为此类的实例。

字符串不变; 它们的值在创建后不能被更改。 字符串缓冲区(StringBuffer)支持可变字符串。 因为String对象是不可变的,它们可以被共享。 例如:

     String str = "abc";
package com.qf.e_string;

public class Demo1 {
	public static void main(String[] args) {
		String str1 = "abc";
		String str2 = new String("abc");
		System.out.println(str1);
		System.out.println(str2);
		System.out.println("======");
		//字符串的值是无法改变
		String str3 = "a";
		System.out.println(str3);//a
		//hashCode方法是十六进制的内存地址的十进制的表示形式
		System.out.println(str3.hashCode());//97
		str3 += "b";
		System.out.println(str3);//ab
		System.out.println(str3.hashCode());//31056
		
		
		System.out.println("---------");
		
		String str4 = new String("abc");
		System.out.println(str4);
		System.out.println(str4.hashCode());
		str4 += "d";
		System.out.println(str4);//abcd
		System.out.println(str4.hashCode());
		
	}
}

字符串的方法

需求:比较两个字符串是否相等

equals方法 内容是否相等

String str1  = "abc";
String str2 = "abd";
char[] v1 = {'a', 'b', 'c'};
char[] v2 = {'a', 'b', 'd'};
while () {
	v1[i] == v2[i]
}
package com.qf.e_string;

public class Demo2 {
	public static void main(String[] args) {
		String str1  = "abc";
		String str2 = "abc";
		String str3 = new String("abc");
		//==  是否相等  比较的是内存地址, 比较严格
		System.out.println(str1 == str2); //true
		System.out.println(str1 == str3);// false
		//equals 先比较两个字符串的内存地址,如果内存地址 返回true
		//如果内存地址不一样   再比较值
		System.out.println(str1.equals(str2));//true
		System.out.println(str1.equals(str3));//true
		//发现equals(Object anObject)
		//equals(new String("abc"))
		//Object 类是所有类的超类
		System.out.println(str2.equals(str3));
		//总结:  string  比较两个方法的时候用  equals方法
	}
}

作业: 练习String方法

int  length();
char   charAt(int index);
int  indexOf(char ch);
int lastIndexOf(char ch);
boolean  endsWith(String str);  是否以指定的字符或者字符串结尾

boolean  startsWit(Strinf str);是否以指定的字符或者字符串开头

boolean  isEmpty();判断是否为空

boolean contains(String str);判断一个字符串的内容是否包含另外一个子字符串

boolean  equals(Object anOtherObj);  判断两个字符串是否相等

boolean  equalsIgnoreCase();忽略大小写,判断两个字符串是否相等
char[]  toCharArray();
String(char[] ch);

String(char[] ch, int offset, int count);

static valueOf(char[] ch);[重点]
String replace(char oldChar, char  newChar);字符串的替换

String replaceAll(String regex, String original);字符串在字符串中替换问题

String[] split(String regex);以指定的字符串切割    k开发用

String subString(int beginIndex);  截取字符串的一部分开发用

String subString(int beginIndex, int endIndex);截取一部分,要头不要尾

String toUpperCase();将小写字母转换为大写字母

String toLowerCase();将大写字母转换为小写字母

  • 26
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值