day05

Java学习day05

面向对象编程opp

opp其实是一种编程思维,在现实世界里,一切都是对象,每个对象都有属性和方法。opp其实就是把这些写成代码。

用我的c语言知识来浅薄的理解,类就是函数和结构体的结合体。

封装与继承

opp有四大特征,今天我学了其中的封装与继承,这两个特征并不算难,很好理解。

封装就是把属性和方法打包在一起,对外只暴露必要接口。这可以更安全,简洁,更易维护。

继承就是子类可以继承父类的属性和方法。这可以极大程度的减少重复代码,层次也更加清晰。

例如:

学生 → 人类

学生就是人类可以直接继承人类的属性,比如年龄性别等,直接减少了代码量。

复习

今天依旧复习写代码,事实证明只听课不写代码根本无法发现问题。

第 1 题:类与对象(面向对象基础)

题目:定义一个 Student 类:

  1. 属性:姓名、年龄、成绩
  2. 方法:showInfo() —— 输出学生所有信息
  3. 在主方法中创建 2 个学生对象并调用方法展示信息

要求

  • 正确写类、属性、构造方法
  • 主方法测试

进阶挑战题(可选,想提升就做)

第 6 题:循环嵌套(进阶)

题目:打印 9×9 乘法表。

public class topic01 {
    public static void main(String[] args)
    {
        Student s1 = new Student();
        Student s2 = new Student();
        s1.name="xiaoming";
        s1.ages=10;
        s1.marks=99;
        s2.name="xiaohong";
        s2.ages=10;
        s2.marks=99;
        s1.showInfo();
        s2.showInfo();
    }
}
public class Student {
    String name;
    int ages;
    int marks;

    public void showInfo() {
        System.out.println(this.name);
        System.out.println(this.ages);
        System.out.println(this.marks);
    }
}

public class topic_plus {
    public static void main(String[] args)
    {
        for(int i=1;i<10;i++)
        {
            for(int j=1;j<=i;j++)
            {
                System.out.print(j+"*"+i+"="+j*i+"\t");
            }
            System.out.println( );
        }
    }
}

posted @ 2026-03-09 20:38  微雨池塘见  阅读(9)  评论(0)    收藏  举报