尚硅谷_Java零基础教程(面向对象中)--学习笔记(十三)

多态性

package com.atguigu.java;
/*
    不能调子类所特有的方法、属性
    有了对象的多态性以后,内存中实际上加载了子类特有的属性和方法的,但是由于变量声明为父类类型,导致编译时,只能调用父类中声明的属性和方法。子类特有的属性和方法不能调用。
    如何才能调用子类特有的属性和方法?
    向下转型:使用强制类型转换。
    Man m1 = (Man)p2;
    向下转型-使用instanceof判断
    向上转型-多态
    使用强转时,可能出现ClassCastException的异常;

    instanceof关键字的使用
    a instanceof A:判断对象a是否是类A的实例。如果是,返回true;如果不是,返回false;
    使用情景:为了避免在向下转型时出现ClassCastException的异常,我们在向下转型之前,先进行instanceof的判断,一旦返回true,就进行向下转型。如果返回false,不进行向下转型。
    如果a instanceof A 返回true,则a instanceof B也返回true。其中类B是类A的父类。
 */
public class InstanceofTest {

}
package com.atguigu.exer;
/*
    1、若子类重写了父类的方法,就意味着子类里定义的方法彻底覆盖了父类同名方法,系统将不可能把父类里的方法转义到子类中:编译看左边,运行看右边。
    2、对于实例变量则不存在这样的现象,即使子类里定义了与父类完全相同的实例变量,这个实例变量依然不可能覆盖父类中定义的实例变量:编译运行都看左边。
 */
class Base{
    int count = 10;
    public void display(){
        System.out.println(this.count);
    }
}

class Sub extends Base{
    int count = 20;

    public void display(){
        System.out.println(this.count);
    }
}

public class FieldMethodTest {
    public static void main(String[] args){
        Sub s = new Sub();
        System.out.println(s.count);
        s.display();
        Base b = s;
        //==,对于引用数据类型来讲,比较的是两个引用数据类型变量的地址值是否相同。
        System.out.println(b == s);
        System.out.println(b.count);
        b.display();
    }
}
package com.atguigu.exer;

public class InstanceTest {
    public static void main(String[] args){
        InstanceTest  test = new InstanceTest();
        test.method(new Person());
    }

    public void method(Person e){
        //虚拟方法的的重载
        String info = e.getInfo();
        System.out.println(info);

        if(e instanceof Graduate){
            System.out.println("Graduate");
        }else if(e instanceof Student){
            System.out.println("Student");
        }else{
            System.out.println("Person");
        }
    }
}

class Person{
    protected String name="Person";
    protected int age = 50;

    public String getInfo(){
        return "Name:" + name + "\n" + "age:" + age;
    }
}

class Student extends Person{
    protected String school = "pku";
    public String getInfo(){
        return "Name:" + name +"\n" + "age:" + age + "\nschool:" + school;
    }
}

class Graduate extends Student{
    public String major = "IT";
    public String getInfo(){
        return "Name:" + name +"\nage:" + age + "\nschool:" + school +"\nmajor" + major;
    }
}
package com.atguigu.exer;

public class Geometric {
    protected String color;
    protected double weight;

    public Geometric(String color, double weight){
        super();
        this.color = color;
        this.weight = weight;
    }

    public String getColor(){
        return this.color;
    }

    public void setColor(String color){
        this.color = color;
    }

    public double getWeight(){
        return this.weight;
    }

    public void setWeight(double weight){
        this.weight = weight;
    }

    public double findArea(){
        return 0.0;
    }
}
package com.atguigu.exer;

public class Circle extends Geometric{
    private double radius;
    public Circle(String color, double weight, double radius){
        super(color, weight);
        this.radius = radius;
    }

    public double getRadius(){
        return this.radius;
    }

    public void setRadius(double radius){
        this.radius = radius;
    }

    public double findArea(){
        return Math.PI * this.radius * this.radius;
    }
}
package com.atguigu.exer;

public class MyRectangle extends Geometric{

    private double width;
    private double height;

    public MyRectangle(String color, double weight, double width, double height){
        super(color, weight);
        this.width = width;
        this.height = height;
    }

    public double getWidth(){
        return this.width;
    }

    public void setWidth(double width){
        this.width = width;
    }

    public double getHeight(){
        return this.height;
    }

    public void setHeight(double height){
        this.height = height;
    }

    public double findArea(){
        return this.width * this.height;
    }
}
package com.atguigu.exer;

public class GeometricTest {

    public static void main(String[] args){
        GeometricTest test = new GeometricTest();

        Circle c1 = new Circle("red", 1.0, 2.3);
        test.displayGeometric(c1);

        Circle c2 = new Circle("red", 1.0,3.3);
        System.out.println(test.equalsArea(c1, c2));
    }

    public boolean equalsArea(Geometric o1, Geometric o2){
        return o1.findArea() == o2.findArea();
    }

    public void displayGeometric(Geometric o){
        System.out.println(o.findArea());
    }
}
package com.atguigu.java;
/*
 * java.lang.Object类
 * 1、Object类是所有Java类的根父类
 * 2、如果在类的声明中未使用extends关键字指明其父类,则默认父类为java.lang.Object类
 * 3、Object类中的功能(属性、方法)就具有通用型
 * 	属性:无
 * 	方法:eauals()、toString()、getClass()、hashCode()、clone()、finalize()、wait()、notify()、notifyAll();
 * 4、Object类只声明类一个空仓的构造器。
 * 
 * 面试题:final、finally、finalize的区别?
 */
public class ObjectTest {

}
package com.atguigu.java;
/* 
 * 面试题:==和equals的区别?
 * 一、回顾==的使用
 * ==:运算符
 * 1、可以使用在基本数据类型变量和引用数据类型变量中;
 * 2、如果比较的是基本数据类型变量:比较两个变量保存的数据是否相等(不一定类型要相同,自动类型提升,不与boolean玩)
 * 3、如果比较的是引用类型变量:比较的是两个对象的值是否相同。即两个引用是否指向同一个对象实体。
 *
 * 二、equals方法的使用
 * 1、是一个方法,而非运算符
 * 2、只能适用于引用数据类型
 * 3、Object类中中equals()方法的定义:
 * public boolean equals(Object obj){
 * 		return (this == obj);
 * }
 * 说明:Object类中定义的equals()和==的作用是相同的。
 * 4、像String、Date、File、包装类都重写了Object类中的equals方法,重写以后,比较的不是两个引用的地址是否相同,而是比较两个对象的实体内容是否相同。
 	5.通常情况下,我们自定义的类如果使用equals()的话,也通常是比较两个对象的"实体内容"是否相同。那么,我们就需要对Object类中的equals方法进行重写。
    重写的原则:比较两个对象的实体内容是否相同。

    补充:==符号使用时,必须保证符号左右两边的变量类型一致。
 */
public class EqualsTest {
    String name;
    int age;

    public boolean equals(Object obj){
        if(this == obj){
            return true;
        }
        if(obj instanceof EqualsTest){
            EqualsTest cust = (EqualsTest)obj;
//            if(this.age == cust.age && this.name.equals(((EqualsTest) obj).name)){
//                return true;
//            }else{
//                return false;
//            }
            return (this.age == cust.age && this.name.equals(((EqualsTest) obj).name));
        }
        return false;
    }
}
package com.atguigu.exer1;

public class OrderTest {
    public static void main(String[] args){
        Order order1 = new Order(1001, "AA");
        Order order2 = new Order(1001, "BB");
        System.out.println(order1.equals(order2));

        Order order3 = new Order(1001, "BB");

        System.out.println(order2.equals(order3));
    }
}

class Order{
    private int orderId;
    private String orderName;

    public void setOrderId(int orderId){
        this.orderId = orderId;
    }

    public int getOrderId(){
        return this.orderId;
    }

    public void setOrderName(String orderName){
        this.orderName = orderName;
    }

    public String getOrderName(){
        return this.orderName;
    }

    public Order(int orderId, String orderName){
        this.orderId = orderId;
        this.orderName = orderName;
    }

    public boolean equals(Object obj){
        if(this == obj){
            return true;
        }

        if(obj instanceof Order){
            Order order = (Order)obj;

            return this.orderId == order.orderId && this.orderName.equals(order.orderName);
        }

        return false;
    }
}
package com.atguigu.exer;

public class GeometricObject {
	protected String color;
	protected double weight;
	
	public GeometricObject() {
		super();
		this.color = "white";
		this.weight = 1.0;
	}

	public GeometricObject(String color, double weight) {
		super();
		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;
	}	
}
package com.atguigu.exer;

public class Circle extends GeometricObject{
	private double radius;

	public Circle() {
		super();
		this.radius = 1.0;
	}

	public Circle(double radius) {
		super();
		this.radius = radius;
	}
	
	public Circle(double radius, String color, double weight) {
		super(color, weight);
		this.radius = radius;
	}

	public double getRadius() {
		return radius;
	}

	public void setRadius(double radius) {
		this.radius = radius;
	}
	
	public double findArea() {
		return 3.14*radius*radius;
	}
	
	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;
	}
	
	public String toString() {
		return "Circle [radius = " +radius+"]";
	}
}
package com.atguigu.exer;

public class CircleTest {
	public static void main(String[] args) {
		Circle circle1 = new Circle(2.3);
		Circle circle2 = new Circle(2.3, "white", 2.0);
		
		System.out.println(circle1.getColor().equals(circle2.color));
	
		System.out.println(circle1.equals(circle2));
		
		System.out.println(circle1);
	}
}
package com.atguigu.java;
/*
 * Java中的JUnit单元测试
 * 
 * 步骤:
 * 1、选择当前工程-右键选择:build path - add libraries - JUnit 4
 * 2、创建java类,进行单元测试。
 * 		此时java类要求:(1)此类是public(2)此类提供一个公共无参的构造器
 * 3、此类中去声明单元测试方法:
 * 		此时的单元测试方法:方法的权限是public,没有返回值,没有形参。
 *
 * 4、此单元测试方法上需要声明@Test结构,并在单元测试类中导入:import org.junit.Test;
 *
 * 5、声明好单元测试方法后,就可以在方法体内测试相关代码。
 * 6、写完代码以后,右键单元测试方法名,run as- JUnit Test
 * 
 * 说明:
 * 1、如果执行结果没有任何异常,绿条。
 * 2、如果执行结果出现异常:红条。
 */
public class JUnitTest {

}
package com.atguigu.java;

/*
 * 包装类的使用
 * 1、java提供了8种基本数据类型对应的包装类,使得基本数据类型的变量具有类的特征。
 *
 * 2、掌握:基本数据类、包装类、String三者之间的转换.
 * 
 * JDK5.0新特性:自动拆箱与装箱;
 */
public class WrapperTest {
	public static void main(String[] args) {
		//基本数据类型如何转换为包装类:调用包装类的构造器。
		
		int num1 = 10;
		Integer in1 = new Integer(num1);
		System.out.println(in1.toString());
		
		Integer in2 = new Integer("123");
		System.out.println(in2.toString());
		
		Float f1 = new Float(12.3f);
		Float f2 = new Float("12.3");
		System.out.println(f1);
		System.out.println(f2);
		
		Boolean b1 = new Boolean(true);
		Boolean b2 = new Boolean("true123");
		System.out.println(b2);
		
		Order order = new Order();
		System.out.println(order.isMale);
		System.out.println(order.isFemale);
		
		
		//包装类->基本数据类型:调用包装类的xxxValue()
		
		int i1 = in1.intValue();
		System.out.println(i1);
		float f = f1.floatValue();
		System.out.println(f1);
		
		// 自动装箱
		Integer int1 = 10;
		Boolean b3 = true;
		
		// 自动拆箱
		System.out.println(int1);
		
		// 基本数据类型、包装类->String类型:调用String重载的valueOf()
		int num2 = 10;
		// 方式一:连接运算
		String str1 = num1 + "";
		// 方式二:调用String的valueOf();
		float f4 = 12.3f;
		String str2 = String.valueOf(f4);
		
		Double d1 = new Double(12.4);
		String str3 = String.valueOf(d1);
		System.out.println(str3);
		
		// String类型->基本数据类型、包装类:调用包装类的parseXxx()
		String str4 = "123";
		//可能会报:NumberFormatException
//		int num1 = (int)str4;
		int num5 = Integer.parseInt(str4);
		System.out.print(num5);
	}
}

class Order{
	boolean isMale;
	Boolean isFemale;
}
package com.atguigu.java;

public class InterviewTest {
	
	public static void main(String[] args) {
		Integer i = new Integer(1);
		Integer j = new Integer(1);
		System.out.println(i == j);
		
		/*
		 * Integer内部定义类IntegerCache结构,IntegerCache中定义类Integer[],保存了从-128~127范围内的整数,如果我们使用自动装箱的方式,给Integer赋值的范围在-128~127,可以直接使用数组中的元素,不用再去new类。目的,提高效率。
		 */
		Integer m = 1;
		Integer n = 1;
		System.out.println(m == n);
		
		Integer x = 128; //相当于new了一个Integer对象
		Integer y = 128;
		
		System.out.println(x == y);
	}
}
package com.atguigu.exer;

import java.util.Scanner;
import java.util.Vector;

public class ScoreTest {
	public static void main(String[] args) {
		//1.实例化Scanner,用于从键盘获取学生成绩
		Scanner scan = new Scanner(System.in);
		//2.创建Vector对象
		Vector v = new Vector();
		//3.通过for(;;)或while(true)方式:给Vector中添加数据
		int maxScore = 0;
		for(;;) {
			System.out.println("请输入学生成绩(以负数代表输入结束)");
			int score = scan.nextInt();
			//4.当输入是负数时,跳出循环
			if(score < 0) {
				break;
			}
			
			if(score > 100) {
				System.out.println("输入的数据非法,请重新输入");
				continue;
			}
			v.addElement(score);
			//5.获取学生成绩当最大值
			if(maxScore < score) {
				maxScore = score;
			}
		}
		//6.遍历Vector,得到每个学生的成绩,并与最大成绩比较得到每个学生的等级。
		char level;
		for(int i=0; i<v.size();i++) {
			Object obj = v.elementAt(i);
			Integer inScore = (Integer)obj;
			int score = inScore;
			
			if(maxScore - score <= 10) {
				level = 'A';
			}else if(maxScore - score <= 20) {
				level = 'B';
			}else if(maxScore - score <= 30) {
				level = 'C';
			}else {
				level = 'D';
			}
			
			System.out.println(i + "" + score + level);
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值