Java基础:类与对象详解及实例

需积分: 10 0 下载量 185 浏览量 更新于2024-09-03 收藏 1KB TXT 举报
Java基础,特别是类与对象的概念在编程中扮演着核心角色。Java作为一种面向对象的编程语言,它的核心思想就是通过创建类来组织和管理数据以及相关的操作。在给定的代码片段中,我们看到了一个名为"Student"的基本Java类的定义。 **类与对象的理解:** - **类(Class)**:类是对一类具有相同特征和行为的实体的抽象。在Java中,定义一个类就像创建了一个蓝图或模板,用来描述对象的属性(数据)和行为(方法)。例如,"Student"类可能代表一个学生,其属性包括名字(如"骐程")和分数(score)。 - **属性(Attributes)**:类中的变量(如`public String name = "骐程"; public int score;`)是属性,它们描述了对象的状态。在上面的代码中,`name`是一个字符串类型的属性,表示学生的姓名;`score`是一个整数类型的属性,表示学生的分数。 - **方法(Methods)**:类中的函数是方法,它们定义了对象的行为。例如,`public void study(Course c)`是一个公共方法,它接受一个`Course`类型的参数,并且在执行时更新学生的分数。方法的主体部分包含了执行操作的代码,如`score += c.score;`。 - **对象(Objects)**:对象是类的实例,每个对象都是特定类的一个具体表现。在Java中创建对象的格式是`类名 对象名 = new 类名();`。例如,`Student student1 = new Student();`会创建一个名为`student1`的`Student`对象。 - **构造方法(Constructor)**:构造方法是一种特殊的方法,用于在创建对象时初始化对象的属性。Java中默认有一个无参构造方法(`public Student()`),但在给定的代码中没有显示。构造方法通常不返回任何值,但可以接收参数以设置初始状态。在实际使用中,我们可以自定义构造方法来初始化`name`和`score`等属性。 在`public static void main(String[] args)`这部分,我们看到的是Java程序的主入口点。在这里,通常执行创建对象、调用方法等主要操作。例如,为了使用`study`方法,我们需要先创建一个`Course`对象并传递给`study`方法,如下所示: ```java Student student1 = new Student(); Course course = new Course(); course.score = 85; student1.study(course); ``` 这段代码首先创建了一个`Student`对象`student1`,然后创建了一个`Course`对象并分配了分数。接着,`study`方法被调用,将`course`的分数加到`student1`的分数上。 总结来说,理解Java的基础概念,包括类、对象、属性和方法,对于编写和理解Java程序至关重要。通过实例化对象并调用方法,程序员可以实现对现实世界中的抽象进行操作,这是面向对象编程的核心理念。

public class IdiomProcessor { public static void main(String[] args) { // 读取文件 File file = new File("D:\\yy\\java\\成语接龙\\成语大全\\去重后.txt"); BufferedReader reader = null; HashMap<String, String> idiomMap = new HashMap<String, String>(); try { reader = new BufferedReader(new FileReader(file)); String line; while ((line = reader.readLine()) != null) { String[] parts = line.split("拼音:"); if(parts.length==2) { String idiom = parts[0].trim(); String pinyin = parts[1]; idiomMap.put(idiom, pinyin); } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } // 统计末尾字出现次数 HashMap<String, Integer> countMap = new HashMap<String, Integer>(); for (String idiom : idiomMap.keySet()) { int count=0; for(String otheridiom:idiomMap.keySet()) if(otheridiom.startsWith(idiom.substring(idiom.length() - 1))) count++; countMap.put(idiom, count); //System.out.println(idiom+":"+count); } // 输出结果到文件 File outFile = new File("D:\\yy\\java\\成语接龙\\成语大全\\全量成语处理后.txt"); BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(outFile)); for (String idiom : idiomMap.keySet()) { String pinyin = idiomMap.get(idiom); writer.write(idiom + "拼音:" + pinyin + "可接:" + countMap.get(idiom) + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (writer != null) { writer.close(); } } catch (IOException e) { e.printStackTrace(); } } } }解读代码

2023-06-09 上传