java 5(面向对象中)

java ——面向对象(中)

eclipse快捷键

补全代码:Alt+/

快速修复:Ctrl+1

批量导包:Ctrl+Shift+o

单行注释:Ctrl+/

如何查看源码:Ctrl+选中指定的结构

撤销:Ctrl+z

反撤销:Ctrl+y

继承性(inheritance)

面向对象的特征之二:继承性

关键字:

extends 

1.继承性的好处:

减少了代码的冗余,提高了代码的复用性;

便于功能的扩展;

为之后多态性的使用,提供了前提

2.继承性的格式:

class A extends B{
    
    
    
}

A:子类、派生类、subclass

B:父类、超类、基类、superclass

体现:一旦子类A继承父类B以后,子类A就获取了父类B中声明的所有的属性、方法

特别的,父类中声明为private的属性或方法,子类继承父类以后,仍然认为获取了父类中的私有的结构,只是因为封装性的影响,使得子类不能直接调用父类的结构而已

子类继承父类以后,还可以声明自己特有的属性或方法:实现功能的扩展

子类和父类的关系,不同于子集和集合的关系(子类的功能反而还要更丰富一点)

3.java中关于继承性的规定

​ (1)一个类可以被多个子类继承

​ (2)java中类的单继承性:一个类只能有一个父类

​ (3)子父类是相对的概念

​ (4)子类直接继承的父类,称为直接父类;间接继承的父类称为间接父类

​ (5)子类继承父类以后,就获取了直接父类以及所有间接父类中声明的属性和方法

实例

public class Kids extends ManKind {
    
    
	int yearsOld;
	public void printAge() {
    
    
		System.out.println("yearsOld="+yearsOld);
	}
}
public class ManKind {
    
    
	int sex;
	int salary;
	public void manOrWoman(int sex) {
    
    
		if(sex==1) {
    
    
			System.out.println("man");
		}
		if(sex==0) {
    
    
			System.out.println("woman");
		}
	}
}
public class KidsTest {
    
    
	public static void main(String[] args) {
    
    
		Kids someKid=new Kids();
		someKid.salary=0;
		someKid.sex=1;
		someKid.yearsOld=18;
		someKid.manOrWoman(1);
	}
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FExQyntp-1678689658069)(E:\Typora图片\image-20221008210806611.png)]

public class Circle {
    
    
	private double radius;
	//空参构造器
	public Circle() {
    
    
		
	}
	public Circle(double radius) {
    
    
		radius=1;
	}
	public void setRadius(double radius) {
    
    
		this.radius=radius;
	}
	public double getRadius() {
    
    
		return radius;
	}
	public double findArea() {
    
    
		return 3.14*radius*radius;
	}
}
public class Cylinder extends Circle{
    
    
	private double length;
	
	public Cylinder() {
    
    
		this.length=1;
	}
	public void setLength(double length) {
    
    
		this.length=length;
	}
	public double getLength() {
    
    
		return length;
	}
	public double findVolume() {
    
    
		return findArea()*length;
	}
}
public class CylinderTest {
    
    
	public static void main(String[] args) {
    
    
		Cylinder c=new Cylinder();
		c.setRadius(2);
		c.setLength(2);
		c.findVolume();
		System.out.println("面积为:"+c.findVolume());
	}
}

表示3.14还可以用:

Math.PI

Object类的理解

1.如果我们没有显式的声明一个类的父类的话,则此类继承于java.lang.Object类

2.所有的java类(除了java.lang.Object类之外)都直接或间接的继承于java.lang.Object类

3.意味着,所有的java类具有java.lang.Object类声明的功能

方法的重写(override/overwrite)

1.定义:子类继承父类以后,可以对父类中同名同参数的方法,进行覆盖操作

2.应用:重写以后,当创建子类对象以后,通过子类对象调用子父类中同名同参数的方法时,实际执行的是子类重写父类的方法

3.重写的规定:

​ 方法的声明 :权限修饰符 返回值类型 方法名(形参列表)throws异常的类型{

​ 方法体

​ }

​ 约定俗成:子类中的叫重写的方法,父类中的叫被重写的方法

​ (1)子类重写的方法的方法名和形参列表与父类被重写的方法的方法名和形参列表相同

​ (2)子类重写的方法的权限修饰符不小于父类被重写的方法的权限修饰符(用覆盖来形象的理解)

​ 特殊情况:子类不能重写父类中声明为private权限的方法

​ (3)返回值类型:

​ 如果父类被重写的方法的返回值类型是void,则子类重写的方法的返回值类型只能是void

​ 如果父类被重写的方法的返回值类型是A类型(Object),则子类重写的方法的返回值类型可以 是A类或A类的子类(String)

​ 如果父类被重写的方法的返回值类型是基本数据类型(比如:double),则子类重写的方法的 返回值类型必须是相同的基本数据类型(必须也是double)

​ (4)子类重写的方法抛出的异常类型不大于父类被重写的方法抛出的异常类型

子类和父类中同名同参数的方法要么都声明为非static的(考虑重写),要么都声明为static的(不是重写)(static不能被覆盖)

正真的开发当中用不着那么麻烦!

面试题:区分方法的重载和重写

测试四种权限修饰符

image-20221008220333596

一般的开发中,还是private和public用的最多

super关键字

1.super理解为:父类的

2.super可以用来调用:属性、方法、构造器

3.super的使用:调用属性和方法

​ 3.1我们可以在子类的方法或构造器中,通过"super.属性"或"super.方法"的方式,显式的调用父类中声明的属性或方法。但是,通常情况下,我们习惯省略"super"

​ 3.2特殊情况:当子类和父类中定义了同名的属性时,我们想要在子类中调用父类中声明的属性,则必须显式的使用"super.属性"的方式,表明调用的是父类中声明的属性

​ 3.3特殊情况: 当子类重写了父类中的方法以后,我们想在子类的方法中调用父类中被重写的方法时,则必须显式的使用"super.方法",表明调用的是父类中被重写的方法

【总结】:出现同名的属性和方法了

this
super

4.super的使用:调用构造器

​ 4.1我们可以在子类的构造器中显式的使用“super(形参列表)”的方法,调用父类中声明的指定的构造器

​ 4.2”super(形参列表)“的使用,必须声明在子类构造器的首行

​ 4.3我们在类的构造器中,针对于”this(形参列表)“或”super(形参列表)“只能二选一,不能同时出现

​ 4.4在构造器的首行,没有显式的声明”this(形参列表)“或”super(形参列表)“,则默认调用的是父类中空参的构造器:super();
​ 4.5在类的多个构造器中,至少有一个类的构造器中使用了”super(形参列表)“,调用父类中的构造器(不可能全是this)

子类对象的实例化过程

1.从结果上来看

​ 子类继承父类以后,就获取了父类中声明的属性或方法

​ 创建子类的对象,在堆空间中,就会加载所有父类中声明的属性

2.从过程上来看:

​ 当我们通过子类的构造器创建子类对象时,我们一定会直接或间接的调用其父类的构造器,进而调用父类的父类的构造器,知道调用了java.lang.Object类中空参构造器为止。正因为加载过所有的父类的结构,所以才可以看到内存中有父类中的结构,子类对象才可以考虑进行调用

明确:虽然创造子类对象时,调用了父类的构造器,但是自始至终只new了一个对象

面向对象特征之三:多态性

1.理解多态性:可以理解为一个事物的多种形态

对象的多态性:父类的引用指向子类的对象

Person p1=new Person();
Person p2=new Man();       //Man是person的子类
Person p3=new Woman();	   //Woman是person的子类

2.何为多态性:

对象的多态性:父类的引用指向子类的对象(或子类的对象赋给父类引用)

3.多态的使用:虚拟方法调用

​ 有了对象的多态性以后,我们在编译期,只能调用父类中声明的方法,但在运行期,我们执行的是子类重写父类的方法(不能调用子类特有的方法或属性

【总结】:编译看左边,运行看右边

4.多态性的使用前提:类的继承关系、方法的重写

5.对象的多态性:只适用于方法,不适用于属性(运行和编译都看左边)

再谈虚拟方法调用

1.正常方法调用:定义什么方法就new什么方法

2.虚拟方法调用:子类中定义了与父类同名同参数的方法,在多态情况下,将此父类的方法称为虚拟方法。父类根据赋予给它不同的子类对象,动态调用属于子类的该方法。这样的方法调用在编译期是无法确定的(运行时行为)

Person p2=new Man();       //Man是person的子类
Person p3=new Woman();	   //Woman是person的子类

3.测试:虚拟方法调用时运行时行为还是编译时行为

import java.util.Random;

//判断虚拟内存调用是编译时行为还是运行时行为

class animal {
    
    
	public void eat() {
    
    
		System.out.println("animal eat food");
	}
}

class cat extends animal {
    
    
	// 重写
	public void eat() {
    
    
		System.out.println("cat eat fish");
	}
}

class dog extends animal {
    
    
	// 重写
	public void eat() {
    
    
		System.out.println("dog eat bone");
	}
}

class pig extends animal {
    
    
	// 重写
	public void eat() {
    
    
		System.out.println("pig eat others");
	}
}

public class Virtual_method {
    
    
	public static animal getInstance(int key) {
    
    
		switch (key) {
    
    
		case 0:
			return new cat();
		case 1:
			return new dog();
		default:
			return new pig();
		}
	}
	public static void main(String[] args) {
    
    
		int key = new Random().nextInt(3);
		System.out.println(key);
		animal a = getInstance(key);
		a.eat();
	}
}

image-20221009212334605

image-20221009212345093

如图可知,由于随机数的产生,我们在运行之前(编译时)并不能确定a.eat()运行的结果,即:

//其中cat、dog、pig是animal的子类
animal a =new cat();
animal a =new dog();
animal a =new pig();
//都是要运行之后才知道调用的是谁

instanceof操作符

1.引入:有了对象的多态性以后,内存中实际上是加载了子类特有的属性和方法的,但是由于变量声明为父类类型,导致编译时,只能调用父类中声明的属性和方法,而子类特有的属性和方法不能调用

那么,如何才能调用子类特有的属性和方法呢?

Person p=new Man();   //Man是Person的子类
Man m=(Man)p;         //向下转型:使用强制类型转换符

image-20221009214449614

但是,使用强转时,可能会出现ClassCastException的异常

因此我们这里引入了instanceof

2.instanceof关键字的使用

a instanceof A 

作用:判断对象a是否时类A的实例,如果是则返回true;如果不是,返回false

使用情境:为了向下转型时出现出现ClassCastException的异常,我们在向下转型之前,先进行instanceof的判断,一旦返回true,就进行向下转型;如果返回false则不向下转型

如果a instanceof A返回ture,则a instanceof B也返回true(其中B是A的父类)

向下转型的几个常见问题

问题一:编译时通过,运行时不通过

Person p1=new Woman();
Man m1=(Man)p1;
Person p2=new Person();
Man m2=(Man)p2;

问题二:编译通过,运行也通过

Object obj=new Woman();
Person p=(Person)obj;

问题三:编译不通过

Man m3=new Woman();  //man和woman是没有关系的 

【总结】:你要向下转型,首先你要new的就是他本身的对象(要转的对象),或者是new一个它子类的对象

练习

image-20221010085507132

public class GeometricObject {
    
    
	String color;
	double weight;
	//空参构造器,防止extends报错
	public GeometricObject() {
    
    
		
	}
	public GeometricObject(String color,double weight) {
    
    
		this.color=color;
		this.weight=weight;
	}
	public void setColor(String color) {
    
    
		this.color=color;
	}
	public String getColor() {
    
    
		return color;
	}
	public double getWeight() {
    
    
		return weight;
	}
	public void setWeight(double weight) {
    
    
		this.weight = weight;
	}
	public double findArea() {
    
    
		return 0;
	}
}
public class Circle extends GeometricObject {
    
    
	private double radius;
	public Circle(double radius,String color,double weight) {
    
    
		super();
		this.radius=radius;
	}
	public double getRadius() {
    
    
		return radius;
	}
	public void setRadius(double radius) {
    
    
		this.radius = radius;
	}
	public double findArea() {
    
    
		return Math.PI*radius*radius;
	}
}
public class MyRectangle extends GeometricObject {
    
    
	private double width;
	private double height;
	public MyRectangle(double width,double height,String color,double weight) {
    
    
		super();
		this.width=width;
		this.height=height;
	}
	public double getWidth() {
    
    
		return width;
	}
	public void setWidth(double width) {
    
    
		this.width = width;
	}
	public double getHeight() {
    
    
		return height;
	}
	public void setHeight(double height) {
    
    
		this.height = height;
	}
	public double findArea() {
    
    
		return width*height;
	}
}
public class GeometricTest {
    
    
	public static void main(String[] args) {
    
    
		GeometricTest t=new GeometricTest();
		Circle c1=new Circle(2,"white", 1);
		t.displayGeometricObject(c1);
		Circle c2=new Circle(3,"white", 1);
		t.displayGeometricObject(c2);
		boolean isEquals=t.equalsArea(c1, c2);
		System.out.println("c1和c2的面积是否相等:"+isEquals);
	}
	
	public boolean equalsArea(GeometricObject o1, GeometricObject o2) {
    
    
		return o1.findArea() == o2.findArea();
	}
	public void displayGeometricObject(GeometricObject o) {
    
    
		System.out.println("面积为:"+o.findArea());
	}
}

Object类的使用

1.Object类是所有Java类的根父类

2.如果在类的声明中未使用extends关键字指明其父类,则默认父类为java.lang.Object类

3.Object类中的功能(属性、方法)就具有通用性

4.Object类只声明了一个空参的构造器

equals()的使用

回顾==的使用

1.可以使用在基本数据类型变量和引用数据类型变量中

2.如果比较的是基本数据类型变量:比较两个变量保存的数据(字符对应ASCII码)是否相等(不一定类型要相同:自动类型提升)

如果比较的是引用数据类型变量:比较两个对象的地址是否相同(看new),即两个引用是否指向同一个对象实体

补充:==符号使用时,必须保证符号左右两边变量类型要一致(能统一在一起)

例如boolean类型与int类型就不能用==来比较(无法统一)

equals()方法的使用

//A,B是两个对象
A.equals(B);    //返回类型是一个boolean型

1.equals()是一个方法,而非运算符

2.只能适用于引用数据类型

3.Object类中equals()的定义:和==的作用是相同的

4.像String、Date、File、包装类都重写了Object类中的equals()方法;重写以后,比较的不是两个引用的地址是否相同,而是比较两个对象的“实体内容”是否相同

5.通常情况下,我们自定义的类如果使用equals()的话,也通常是比较两个对象的实体内容是否相同,那么我们就需要对Object类中的equals()进行重写

重写的原则:比较两个对象的实体内容是否相同

自动生成equals()

@Override
public boolean equals(Object obj) {
    
    
	if (this == obj)
		return true;
	if (obj == null)
		return false;
	if (getClass() != obj.getClass())
		return false;
	customer2 other = (customer2) obj;
	return id == other.id && Objects.equals(name, other.name);
}

【总结】:我们用String时,来equals()是比较的内容,而我们自己定义的类型却不是这样,因此在实际开发中,我们需要用系统提供给我们的重写的equals()方法来比较内容

为什么Object提供的equals这么简略——因为它不知道你自己定义的属性有哪些!

练习

image-20221010162010400

public class Order {
    
    
	private int orderId;
	private String orderName;
	//空参构造器
	public Order() {
    
    
		
	}
	//两个参数的构造器
	public Order(int orderId,String orderName) {
    
    
		this.orderId=orderId;
		this.orderName=orderName;
	}
	public int getOrderId() {
    
    
		return orderId;
	}
	public void setOrderId(int orderId) {
    
    
		this.orderId = orderId;
	}
	public String getOrderName() {
    
    
		return orderName;
	}
	public void setOrderName(String orderName) {
    
    
		this.orderName = orderName;
	}
	@Override
	//判断测试类的两个对象是否相等
	public boolean equals(Object obj) {
    
    
		if(this==obj) {
    
    
			return true;
		}
		if(obj instanceof Order) {
    
    
			Order o=(Order)obj;
			return this.orderId==o.orderId&&this.orderName.equals(o.orderName);
		}
		return false;
	}
}

toString()方法

Object类中toString()方法的使用:

1.当我们输出一个对象的引用时,实际上是调用当前对象的toString()方法

public class toStringTest {
    
    
	public static void main(String[] args) {
    
    
		Order o=new Order();
		System.out.println(o.toString());
		System.out.println(o);
	}
}

image-20221010165420793

2.Object类中toString()的定义:

public String toString() {
    
    
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

3.像String、Date、File、包装类等都重写了Object类中的toString()方法

​ 使得在调用对象的toString()时,返回“实体内容”信息

String str=new String("hello");
	System.out.println(str.toString());
Date date=new Date(2131231223L);
	System.out.println(date.toString());

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TwSkpbkt-1678689658072)(E:\Typora图片\image-20221010170343163.png)]

4.自定义类可以重写toString()方法,当调用此方法时,返回对象的实体内容

@Override
public String toString() {
    
    
	return "Order [orderId=" + orderId + ", orderName=" + orderName + "]";
}

这个比较简单,所有可以直接用系统自带的Source即可

练习

image-20221010171932921

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UeZuJNoY-1678689658072)(E:/Typora图片/image-20221010172422808.png)]

//父类对象
public class GeometricObject {
    
    
	protected String color;
	protected double weight;
	protected GeometricObject() {
    
    
		color="white";
		weight=1.0;
	}
	protected GeometricObject(String color,double weight) {
    
    
		this.color=color;
		this.weight=weight;
	}
	public String getColor() {
    
    
		return color;
	}
	public void setColor(String color) {
    
    
		this.color = color;
	}
	public double getWeight() {
    
    
		return weight;
	}
	public void setWeight(double weight) {
    
    
		this.weight = weight;
	}
}
//子类对象
public class Circle extends GeometricObject{
    
    
	private double radius;
	//空参构造器
	public Circle() {
    
    
		
	}
	public Circle(double radius) {
    
    
		super();
		radius=1.0;
	}
	public Circle(String color,double weight,double radius) {
    
    
		this.radius=radius;
	}
	public double getRadius() {
    
    
		return radius;
	}
	public void setRadius(double radius) {
    
    
		this.radius = radius;
	}
	//计算圆的面积
	public double findArea() {
    
    
		return Math.PI*radius*radius;
	}
	@Override
	//比较半径是否相等
	public boolean equals(Object obj) {
    
    
		//先比较当前对象和形参对象的地址是否相等
		if(this==obj) {
    
    
			return true;
		}
		if(obj instanceof Circle) {
    
    
			Circle c=(Circle)obj;
			return this.radius==c.radius;
		}
		return false;
	}
	@Override
	public String toString() {
    
    
		return "Circle [radius=" + radius + "]";
	}
}
//Test类
public class CircleTest {
    
    
	public static void main(String[] args) {
    
    
		Circle c1=new Circle(2.3);
		Circle c2=new Circle("red", 2.0, 2.3);
		//String类型的可以直接用equals,不用重写
		System.out.println("颜色是否相等:"+c1.getColor().equals(c2.getColor()));
		//比较半径就直接用我们重写到的方法
		System.out.println("半径是否相等:"+c1.equals(c2));
	}
}

包装类(Wrapper)的使用

我们希望java中的基本数据类型也具有类的性质(变量就变成了对象)

包装类的使用

java提供了8种基本数据类型对应的包装类,使得基本数据类型的变量具有类的特征

基本数据类型、包装类、String类三者的转换

1.基本数据类型------>包装类:调用包装类的构造器

int num1=10;
Integer in1=new Integer(num1);
Integer in2=new Integer(123);     //right
Integer in3=new Integer(123abc);  //wrong
Float f1=new Float(12.3f);
Float f2=new Float("12.3");   //right
Boolean b1=new Boolean(true);
Boolean b2=new Boolean("true");
Boolean b3=new Boolean("true123"); 
System.out.println(b3);        //输出为:false

2.包装类------>基本数据类型:调用包装类的xxxValue()

Integer in1=new Integer(12);
int i1=in1.intValue();

为什么要转回来——可以做数值上的运算

新特性:自动装箱与自动拆箱

//自动装箱:基本数据类型------>包装类
int num1=10;
Integer in1=num1;

boolean b1=true;
Boolean b2=b1;
//自动拆箱:包装类------>基本数据类型
int num2=in1;

3.基本数据类型和包装类------>String类型:调用String重载的valueOf(Xxx xxx)

由于基本数据类型和包装类具有自动装箱和自动拆箱功能,这里我们将他们看成一起

//方式一:连接运算
int num1=10;
String str1=num1+" ";
//方式二:调用String的valueOf(Xxx xxx)
float f1=12.3f;
String str2=String.valueOf(f1);  //此时为"12.3"

4.String类型------>基本数据类型和包装类:调用包装类的parseXxx(String s)

//在转换之前要确定是否能转换
String str1="123";
int num1=Integer.parseInt(str1);
//特别的,对于布尔型:只要不是true,都认为是false
String str2="ture1";
boolean b1=Boolean.parseBoolean(str2);

image-20221010194533849

猜你喜欢

转载自blog.csdn.net/kevvviinn/article/details/129493829