Java重要知识点(继承、多态、接口,异常,工具,测试)

Java项目课程03:涉及知识点 一、Java基本语法 二、Java流程控制 三 Java面向对象编程 四、Java集合框架 五、Java图形用界面编程 六、MySQL数据库操作 七、Java数据库编程 八、MVC模式分层架构 九、单元测试 阅读详情


重载、多态、接口

多态调用的顺序

当父类,和子类有Static时,先初始化Static,再初始化子类的Static,再初始化父类的其他成员变量->父类构造方法->子类其他成员变量->子类的构造方法。

重写 hashcode equals compareto

Employee.java

import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Objects;

public class Employee implements Comparable<Employee> {
    private String name;
    private double salary;
    private Date hireDay;

    public Employee(String n, double s, int year, int month, int day) {
        name = n;
        salary = s;
        GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
        hireDay = calendar.getTime();
    }

    public String getName() {
        return name;
    }

    public double getSalary() {
        return salary;
    }

    public Date getHireDate() {
        return hireDay;
    }

    public boolean equals(Object Otherobject) {
        if (this == Otherobject)
            return true;
        if (Otherobject == null)
            return false;
        // if(! Otherobject instanceof Employee) return false;
        if (getClass() != Otherobject.getClass())
            return false;
        Employee other = (Employee) Otherobject;
        return Objects.equals(name, other.name) && salary == other.salary && Objects.equals(hireDay, other.hireDay);
    }

    public int hashCode() {
        return Objects.hash(name, salary);
    }

    public String toString() {
        return getClass().getName() + "name=" + name + ",salary=" + salary + ",hireDay=" + hireDay;
    }

    @Override
    public int compareTo(Employee other) {
        // if(getClass() != other.getClass()) throw new ClassCastException();
        return Double.compare(salary, other.salary);
    }
}

Manager.java

public class Manager extends Employee {

    private double bonus;

    public Manager(String n, double s, int year, int month, int day) {
        super(n, s, year, month, day);
        bonus = 0;
    }

    public void setBonus(double b) {
        bonus = b;
    }

    @Override
    public double getSalary() {
        double baseSalary = super.getSalary();
        return bonus + baseSalary;
    }

    @Override
    public boolean equals(Object Otherobject) {
        if (!super.equals(Otherobject))
            return false;
        Manager other = (Manager) Otherobject;
        return bonus == other.bonus;
    }

    @Override
    public int hashCode() {
        return super.hashCode() + 17 * new Double(bonus).hashCode();
    }

    @Override
    public String toString() {
        return super.toString() + ",bonus=" + bonus;
    }
}


异常

涉及return finally 以及异常抛出的问题

这里写图片描述
这里写图片描述

各个异常出现的情况

package exp;

import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.beans.Statement;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Stack;


public class AllExcept {

    public static void main(String[] args) throws Exception {
        // 01 空指针异常 java.lang.NullPointerException
        try {
            int[] s = null;
            int i = s.length;
        } catch (Exception e) {
            System.out.println("1、" + e.getClass().getName() + "异常");
        }
        // 02数组越界 java.lang.ArrayIndexOutOfBoundsException异常
        try {
            int[] s1 = new int[2];
            s1[2] = 5;
        } catch (Exception e) {
            System.out.println("2、" + e.getClass().getName() + "异常");
        }
        // 03 错误类型的对象存储到一个对象数组时抛出的异常 java.lang.ArrayStoreException异常
        try {
            Object x[] = new String[3];
            x[0] = new Integer(0);

        } catch (Exception e) {
            System.out.println("3、" + e.getClass().getName() + "异常");
        }
        // 04 除数为0异常 java.lang.ArithmeticException异常
        try {
            int a = 0;
            int b = 10;
            b /= a;
        } catch (Exception e) {
            System.out.println("4、" + e.getClass().getName() + "异常");
        }
        // 05 数据类型转换异常 java.lang.NumberFormatException异常
        try {
            String s2 = "19k";
            int n = Integer.parseInt(s2);
        } catch (Exception e) {
            System.out.println("5、" + e.getClass().getName() + "异常");
        }
        // 06 超过字符串添加长度异常 java.lang.StringIndexOutOfBoundsException异常
        try {
            StringBuffer buffer = new StringBuffer();
            buffer.charAt(5);
        } catch (Exception e) {
            System.out.println("6、" + e.getClass().getName() + "异常");
        }
        // 07 数组大小为负值异常。 java.lang.NegativeArraySizeException异常
        try {
            int i = -1;
            int[] s = new int[i];
        } catch (Exception e) {
            System.out.println("7、" + e.getClass().getName() + "异常");
        }
        // 08 正则表达式异常 java.util.regex.PatternSyntaxException异常
        try {
            String a = "\\";// 错误的正则表达式
            String a1 = "\\.";// 正确的正则表达式
            String[] x5 = "abc.cde".split(a1);
            x5 = "abc.cde".split(a);

        } catch (Exception e) {
            System.out.println("8、" + e.getClass().getName() + "异常");
        }
        // 09 空栈异常 java.util.EmptyStackException异常
        try {
            Stack s = new Stack();
            s.pop();
        } catch (Exception e) {
            System.out.println("9、" + e.getClass().getName() + "异常");
        }
        // 10 找不到类异常 java.lang.ClassNotFoundException异常
        try {
            Object s = Class.forName("ClassName");
        } catch (Exception e) {
            System.out.println("10、" + e.getClass().getName() + "异常");
        }
        // 11非法参数异常
        // 12 字体格式错误异常
        try {
            Font f = new Font("楷体", Font.BOLD, 7);
            f.createFont(2, new File("1.txt"));
        } catch (FontFormatException e) {
            System.out.println("11、" + e.getClass().getName());
        } catch (IllegalArgumentException e) {
            System.out.println("12、" + e.getClass().getName() + "异常");
        }
        // 13不支持画图异常
        try {
            Image img = Toolkit.getDefaultToolkit().getImage("Images\1.jpg");
            Graphics g = img.getGraphics();
            g.drawRect(-1, -1, -1, -1);
        } catch (Exception e) {
            System.out.println("13、" + e.getClass().getName() + "异常");
        }

        // 14 BufferOverflowException
        try {
            int cap = 2;
            ByteBuffer bf = ByteBuffer.allocate(cap);
            for (int i = 0; i < cap; i++) {
                bf.put((byte) i);
            }
            bf.put((byte) 10);
            bf.getInt(9);
        } catch (Exception e) {
            System.out.println("14、" + e.getClass().getName() + "异常");
        }
        // 15文件找不到异常
        // 16.当发生某种 I/O 异常时,抛出IOException
        // 17.文件已结束异常EOFException
        try {
            File f = new File("E:\\1.txt");
            byte[] buff = new byte[2];
            FileInputStream file = new FileInputStream(f);
            int bytes = file.read(buff, 0, 2);
            System.out.println(new String(buff, 0, 0, bytes));
            file.close();

        } catch (FileNotFoundException e) {
            System.out.println("15、" + e.getClass().getName() + "异常");
        } catch (EOFException e) {
            System.out.println("16、" + e.getClass().getName() + "异常");
        } catch (IOException e) {
            System.out.println("17、" + e.getClass().getName() + "异常");
        }
        // 18 ClassCastException异常
        try {
            Object s = new Integer(0);
            System.out.println((String) s);
        } catch (Exception e) {
            System.out.println("18、" + e.getClass().getName() + "异常");
        }
        // 19 BufferUnderflowException异常
        try {
            ByteBuffer buf = ByteBuffer.allocate(50);
            buf.flip();
            byte[] byt = new byte[100];
            buf.get(byt);

            new RuntimeException();
        } catch (Exception e) {
            System.out.println("19、" + e.getClass().getName() + "异常");
        }
        // 20 java.sql.SQLException异常
        try {

            String sql = "select * from Table";// sql语句错误
            Connection conn = DriverManager.getConnection("com.mysql.jdbc.Driver");

            Statement smt = (Statement) conn.createStatement();
            smt.execute();

        } catch (Exception e) {
            System.out.println("20、" + e.getClass().getName() + "异常");
        }
    }
}


工具

git svn 的 区别 和 常用命令

Maven依赖中的scope

测试

JUnit

Die.java

public class Die
{
    private int faceValue;
    private int numofsides;
    public Die(){
        faceValue = 0;
        numofsides = 6;
    }

    public Die(int v){
        numofsides = v;
    }

    public int numOfSides(){
        return numofsides;
    }


    public int  topFace(){
        return faceValue;
    }

    public void roll() {
        faceValue = (int) (1 + Math.random() * numofsides );
    }
}




TestDie.java

import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.junit.Before;


/**
 * Unit test for simple App.
 */

public class TestDie {

    private Die die1,die2;

    @Before
    public void setUp() {

        die1 = new Die();
        die2 = new Die(10);
        die1.roll();
        die2.roll();
    }

    @Test
    public void testdie1numofsides() {
        Assert.assertEquals(6, die1.numOfSides());
    }

    @Test
    public void testdie1Face() {
        Assert.assertTrue(die1.topFace() >= 1 && die1.topFace() <= 6);
    }

    @Test
    public void testdie2numofsides() {
        Assert.assertEquals(10, die2.numOfSides());
    }

    @Test
    public void testdie2Face() {
        Assert.assertTrue(die2.topFace() >= 1 && die2.topFace() <= 10);
    }

    @After
    public void tearDown() {
    }

}



实现 assertEquals aseertSame

assertEquals.java

当expected和actual都是String类型时,ComparisonFailure还会找出是前后相同的串,并用[Different String]标明那些不相同的字符串,也就是expectedToString和actualToString的格式将会变成:…${sameString}[${differentString}]${sameString}…。其中“…”只会在相同的字符串太长的情况下才会出现,这个长度标准目前(JUnit4.10)是20个字符。具体实现参考ComparisonFailure类,它继承自AssertionError,这里不再展开。

/**
     * Asserts that two objects are equal. If they are not, an
     * {@link AssertionError} is thrown with the given message. If
     * <code>expected</code> and <code>actual</code> are <code>null</code>,
     * they are considered equal.
     * 
     * @param message
     *            the identifying message for the {@link AssertionError} (<code>null</code>
     *            okay)
     * @param expected
     *            expected value
     * @param actual
     *            actual value
     */
        static public void assertEquals(String message, Object expected,
            Object actual) {
        if (expected == null && actual == null)
            return;
        if (expected != null && isEquals(expected, actual))
            return;
        else if (expected instanceof String && actual instanceof String) {
            String cleanMessage= message == null ? "" : message;
            throw new ComparisonFailure(cleanMessage, (String) expected,
                    (String) actual);
        } else
            failNotEquals(message, expected, actual);
    }

    private static boolean isEquals(Object expected, Object actual) {
        return expected.equals(actual);
    }

    /**
     * Asserts that two objects are equal. If they are not, an
     * {@link AssertionError} without a message is thrown. If
     * <code>expected</code> and <code>actual</code> are <code>null</code>,
     * they are considered equal.
     * 
     * @param expected
     *            expected value
     * @param actual
     *            the value to check against <code>expected</code>
     */
    static public void assertEquals(Object expected, Object actual) {
        assertEquals(null, expected, actual);
    }





aseertSame.java

    /**
     * Asserts that two objects refer to the same object. If they are not, an
     * {@link AssertionError} is thrown with the given message.
     * 
     * @param message
     *            the identifying message for the {@link AssertionError} (<code>null</code>
     *            okay)
     * @param expected
     *            the expected object
     * @param actual
     *            the object to compare to <code>expected</code>
     */
    static public void assertSame(String message, Object expected, Object actual) {
        if (expected == actual)
            return;
        failNotSame(message, expected, actual);
    }

    /**
     * Asserts that two objects refer to the same object. If they are not the
     * same, an {@link AssertionError} without a message is thrown.
     * 
     * @param expected
     *            the expected object
     * @param actual
     *            the object to compare to <code>expected</code>
     */
    static public void assertSame(Object expected, Object actual) {
        assertSame(null, expected, actual);
    }




其他

  • hamcrest 可以用来增强 JUnit 中的 assert 功能
  • Cobertura is a free Java tool that calculates the percentage of code accessed by tests.
  • stub & mock. EasyMock has been the first dynamic Mock Object generator, relieving users of hand-writing Mock Objects, or generating code for them
  • DbUnit is a JUnit extension (also usable with Ant) targeted at database-driven projects that,among other things, puts your database into a known state between test runs



本文转自:http://blog.youkuaiyun.com/u011239443/article/details/53150159

Java面向对象编程(OOP)第三阶段深入学习 本文还有配套的精品资源,点击获取 简介:本项目为Java面向对象编程(OOP)的学习课程的第三部分,深入讲解面向对象编程的核心概念和实践应用。涵盖包括类和对象的定义、封装、继承、多态、接口、抽象类、内部类、异常处理、集合框架、文件与I/O流操作、设计模式和单元测试等Java OOP的关键知识点,并通过实战练习加强理解。 1. Java面向对象编程概述 1.1 面... 阅读详情

相关推荐

压电阀控制器设计-总章

本文章用于回顾记录本人制作压电阀控制器的关键技术,本人所制作压电阀控制器已经上市得到应用,特在此对一些关键技术进行回顾记录,欢迎从事压电控制及压电阀相关人员一起讨论

qq_42712859的博客 849

java学习笔记(五)——继承多态及类的转换问题

Employee类:package test;public class Employee { private String name; private int money; public Employee(String name,int money){ this.name=name; this.money=money; } public String getName(){ r

kakaxiaoxing的专栏 585

退火朗之万动力学采样

退火朗之万动力学采样(Simulated Annealing Langevin Dynamics Sampling)结合了退火技术和朗之万动力学,是一种用于分子模拟和统计物理中的计算方法。这种方法可以帮助系统从局部最小值中逃逸,以找到全局最小值或进行有效的配置空间探索。

weixin_39699362的博客 1947

java.util.Objects源码解读

简介: Objects是自jdk1.7起新增的工具类,这个类由一些实用的静态方法组成,这些方法可以方便我们平时的开发,例如对象比较、获取对象的hash码等。 源码解读: 1.类及构造方法 /** * This class consists of {@code static} utility methods for operating * on objects. These util...

小诸葛的博客 683

QuickFix Java 讲解(五)消息的收发与查看

本系列力求手把手教你怎样利用QuickFix Java 搭建自己的 FIX 协议收发平台,以及其中的注意事项。 所有源码的地址(免费): https://github.com/zongzhec/QuickFixPractise 这节我们讨论将Acceptor和Initiator启动以后,收到的消息极其查看方式。 6. 收发双方的通信 6.1. 启动后的通信和登录 为方便起见,这里我们使用统一的源码:https://github.com/zongzhec/QuickFixPractise ..

2245

DaVinciCFG实战:从ARXML配置到ADC代码生成全解析

本文详细解析了使用DaVinciCFG工具进行ADC模块配置的全过程,从ARXML文件处理到代码生成与集成。重点介绍了关键参数配置、ARXML语法规则、常见错误排查及代码优化技巧,帮助开发者掌握AUTOSAR架构下ADC驱动开发,提升汽车电子系统的可靠性。

f9g0h的博客 378

【Java基础】继承 多态 接口 异常 面试场问题

继承 继承为了重用父类的代码,两个类存在is-a(是一种)关系时,可以使用继承,达到代码复用(优点),提高效率 例:猫狗都是动物,都有毛色,习性等特征,可以将其封装到父类anminal java中是否可以多继承? 答:不可以。 为什么不能多继承? 答:(菱形继承)反推 假设存在多继承,A类派生B,C , 则B包含自己的内容和继承过来的内容 a,b ,C同 a,c;如果多继承存在 D继承B和C,则D中会包含a,b a ,c 此时a被复制两份 同一个作用域中,不能出现两份相同的 所以只能单一继承。 方法

xintu1314的博客 246

202505系分论文《论软件系统测试方法及应用》

本文以软件测试方法为切入点,重点论述分层协作、智能赋能、全流程三个维度下传统测试与自动化测试的融合应用。

pccai的博客 1693

【面试题】Java三大特性封装继承多态总结

本文内容总结于多篇博客,参考到的地方在文中都会一一列出 http://www.cnblogs.com/ibalintha/p/3897821.html 1.封装 封装的定义: 首先是抽象,把事物抽象成一个类,其次才是封装,将事物拥有的属性和动作隐藏起来,只保留特定的方法与外界联系 为什么需要封装: 封装符合面向对象设计原则的第一条:单一性原则,一

zjkC050818的博客 1万+

100天精通Python(数据分析篇)——第53天:初识pandas模块_基础介绍

一、初始pandas 1. 什么是pandas? 2. 为什么要学习pandas? 3. pandas的优势 4. 下载安装pandas 二、Pandas的数据类型 1. Series 2. DataFrame

努力让自己发光,对的人才能迎着光而来 17万+

Codex 自定义模型操作指南:CLI 与桌面客户端双端实操

检查版本 codex --version # 预期输出类似:codex-cli 0.133.0-alpha.1 # 如未安装 npm install -g @openai/codex假设你要接入DeepSeek,在# 临时设置(当前终端会话有效)export DEEPSEEK_API_KEY="sk-你的 DeepSeek API Key"# 永久设置(推荐,写入 shell 配置)

篮球界最会写bug的人;程序猿中打球最菜的人。 454

java oop 题目_JavaOOP试题JavaOOP试题.doc

JavaOOP试题JavaOOP试题PAGEPAGE 8JavaOOP 综合测试题(笔试)选择题目共50道,每道题2分,共100分1)以下属于OOP的特征有()。a)继承 b)封装c)多态d)隐藏2)JavaOOP中的多态包括()a)方法重写b)方法重载c)方法隐藏d)以上都不对3)Java中的访问修饰符包括( )。a)Public b)privatec)protectedd)internal4...

weixin_34987818的博客 536

一文读懂5G网络整体架构(接入网+承载网+核心网)

接入网重构分级(分工更细、效率更高)、承载网三段化升级(管道更宽、更智能)、核心网服务化云化(管理更灵活、成本更低)最终实现“成本最优、资源灵活、场景适配”,才能支撑自动驾驶、工业互联网、智慧城市、VR/AR等各种新场景,真正走进我们的生活。

鲸落寰宇 427

Java知识梳理

抽象数据类型与介于接口和具体的类之间,在抽象数据类型中的方法默认需要书写其实现通过abstract语句可以不用编写实现,方法可以是私有的但同样不能被实例化。java中的每个基本类型的变量都对应一个包装类(wrapper calss)也称为引用类,比如在对于一些泛化的类和方法我们在使用的时候会根据需要定义其类型(如Integer)。之后引入sllist,这个类通过嵌套类的方法再原先链表的基础上加入一个中间层操作链表,方便用户调用定义,参数(之前的链表每次加入新的值都需要加入一个指针指向原来首个单元的地址)。

weixin_43871792的博客 884

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

Java强基项目-移动公司业务办理-优快云博客

这篇文章分享了一个用Java模拟移动公司业务办理的小项目,通过面向对象编程实践核心概念。项目模拟移动营业厅套餐办理、通话、短信和上网业务,包含三种套餐(话唠、网虫、超级)及其差异化计费规则。文章详细介绍了项目需求、Maven项目创建、类与接口设计(包括UML类图)、面向对象关键概念(封装、继承、多态、接口)以及代码实现思路。项目适合Java初学者练习面向对象设计、异常处理、枚举、集合等核心知识点,并提供完整的需求分析、类设计和测试场景。

ccoo__n的博客 537

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

Java基础学习笔记整理

String保存的是字符串常量, 里面的值不能更改,每次String类的更新实际 上就是更改地址,效率较低//private final char value[];StringBuffer保存的是字符串变量,里面的值可以更改,每次 StringBuffer的更新实际上可以更新内容,不用每次更新地址,效率较高。StringBuilder和StringBuffer均代表可变的字符序列,方法是一样的,所 以使用和StringBuffer一样。String是一个final类, 代表不可变的字符序列。

易琳的博客 1061

java基础知识

java 基础知识汇总 本篇文章主要记录,我几年前学习java的知识笔记汇总 文章目录java 基础知识汇总一. java常用知识点二、 java常用API 一. java常用知识点 命名规范 类名规范:首字母大写,后边的每个单词首字母大写(大驼峰) 变量名规范:首字母小写,后边的每个单词字母大写(小) 方法名规范:同变量名 数据类型 单引号为字符类型(只可以写一个字符) 双引号为字符串类型 默认的数字为整形,长整形要在数字末尾加L ,浮点型要在数字末尾加F(如果数字超出范围会溢出)

梦想导航 166

周报2>>>

面向对象的特征之继承: 1.使用extends建立子类与父类的继承关系 2.子类继承父类相当于子类把父类的功能复制了一份,但是,构造方法不能被继承。 3.继承后,子类可以使用父类的所有非私有资源,私有资源不可用的原因是不可见。 4.Java只支持单继承,一个子类只能有一个父类,但一个父类可以有多个子类。 5.继承具有传递性,爷爷的功能会传给爸爸,爸爸的功能会传给孙子。 6.继承是强耦合,关联性非常强的 is a 的关系。 关键字Super: 1.Super可以在父类成员变量与子类成员变量同名

bss13287350062的博客 146

Java进阶-思维导图

111

m0_67390788的博客 358

什么是继承和多态,它们在Java中如何工作?

在Java中,使用`extends`关键字来定义继承。例如,我们可以创建一个`Animal`类,然后创建一个`Dog`类来继承`Animal`类。这样,`Dog`类就继承了`Animal`类的属性和方法。

m0_47946173的博客 1072

三、Java面向对象之继承、多态和接口

前面提到static静态,这里紧接着写出继承、多态和接口的相关知识。本文对继承、多态、final关键字用法和抽象类进行了一个介绍,对其注意事项进行了一个简单的说明。

m0_56676311的博客 634

java面向对之象类的继承与多态

类的继承与多态,父类方法重写,super关键字,final关键字,抽象类,接口,对象转换,子类转换成父类,父类转换成子类,instanceof关键字,Object类,局部内部类,静态内部类,匿名内部类,try..catch.finally,throws关键字,自定义异常类

. 1274

Java的多态与接口

java的接口与多态

2403_88874650的博客 1415

继承,接口,多态与异常

​ 继承是Java的第二大特性,是从已有的类中派生出新的类,新的类能吸收已有类的数据属性和行为,并能扩展新的能力。使得子类对象(实例)具有父类的实例域和方法,或子类从父类继承方法,使得子类具有父类相同的行为。​ 在实际应用中,继承为程序开发节省了大量的重复性工作,提高开发效率。例如你想创建一个新的类,这个类中的所有成员变量和成员方法在一个已经存在的类中都有,这时这个新的类可以直接继承自父类,然后再添加子类中特有的变量和方法。值得注意的是,一个子类只能继承自一个父类,毕竟一个儿子不能有多个爹。

guichen0203的博客 137
上一篇: 华为开源数据格式CarbonData项目,实现大数据即席查询秒级响应
下一篇: 深拷贝与浅拷贝(Java)
Footloose_
博客等级 码龄10年 254粉丝 11原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值