Java 面向对象入门

第一章:类与对象

1.1 类与对象

类与对象的定义和使用
在 Java 中定义类,使用关键字 class 完成。语法如下:

class 类名称 { 属性 (变量) ; 行为 (方法) ; }

我们可以通过下面的实例来感受一下如何定义一个 Person 类。

class Person { // 类名称首字母大写 String name ; int age ; public void tell() { // 没有static System.out.println("姓名:" + name + ",年龄:" + age) ; } }

类定义完成之后,是无法直接使用的。如果要使用,必须依靠对象,那么由于类属于引用数据类型,所以对象的产生格式(两种格式)如下:

(1)格式一:声明并实例化对象

类名称 对象名称 = new 类名称 () ;

(2)格式二:先声明对象,然后实例化对象

类名称 对象名称 = null ; 对象名称 = new 类名称 () ;

1.2 完善合适的类

你需要根据 Main.java 文件中的代码,来完善 Solution 类中的相关代码。在 Solution 类中添加 show() 方法打印信息。

class Solution { //write your code here String name; int age; public void show(){ System.out.printf("Name: %s, age: %d",this.name,this.age); } }

1.3 动物园的新朋友

每天动物园都有可能进来新的朋友,为了方便管理员管理,需要对每个动物起一个名字,并记录这个动物的年龄和种类。
请您在 Animal 类中完成该功能:
创建一个 setAnimalMessage(String name, String type, int age) 方法,设置每个动物的信息。
创建一个方法 printAnimalMessage(),打印动物的信息。打印的格式如下:

姓名 is a 种类 and is 年龄 years old this year。
public class Animal { private String name,type; private int age; public void setAnimalMessage(String name, String type, int age) { this.name = name; this.type = type; this.age = age; } public void printAnimalMessage() { System.out.println(name+" is a "+type+" and is "+age+" years old this year."); } }

第二章:属性和方法

2.1属性和方法

我们可以通过下面的实例来感受一下如何使用对象操作类。
(1)格式一:声明并实例化对象

class Person { String name; int age; public void get() { System.out.println("姓名:" + name + ",年龄:" + age); } } public class TestDemo { public static void main(String args[]) { Person per = new Person();//声明并实例化对象 per.name = "张三"; //操作属性内容 per.age = 30; //操作属性内容 per.get(); //调用类中的get()方法 } }

运行结果:
姓名:张三,年龄:30
(2)格式二:先声明对象,然后实例化对象

class Person { String name; int age; public void get() { System.out.println("姓名:" + name + ",年龄:" + age); } } public class TestDemo { public static void main(String args[]) { Person per = null; //声明对象 per = new Person(); //实例化对象 per.name = "张三"; //操作属性内容 per.age = 30; //操作属性内容 per.get(); //调用类中的get()方法 } }

运行结果:
姓名:张三,年龄:30

2.2补充 Student 类的属性和方法

请根据 Main 中对 Student 类的属性和方法的调用,补充 Student 的属性和方法。

public class Student { // write your code here String name; int age; String sex; //定义常量 final static String SEX_FEMALE = "female"; final static String SEX_MALE = "male"; public void setSex(String sex){ this.sex = sex; } //重写toString方法 public String toString(){ return "name = "+name+", age = "+age+", sex = "+sex; } }

2.3 普通单例模式

请实现一个单例模式的类 SingleClass,使 Main 方法可以正确运行。

public class SingleClass { public String toString() { return "This is a Single Instance Class."; } // write your code here //创建 SingleClass 的一个对象 private static SingleClass instance = new SingleClass(); //让构造函数为 private,这样该类就不会被实例化 private SingleClass(){} //获取唯一可用的对象 public static SingleClass getInstance(){ return instance; } }

第三章:构造方法

3.1 无参构造

没有参数的构造函数被称为无参数构造函数,构造函数名称与类名称是匹配的。 构造函数体中可以写任何代码,但是系统默认构造函数的构造函数体是空的。

3.2 无参构造函数的使用(一)

请使用无参构造函数,给 Student 类的属性赋初始值。name = Tom、age = 20、height = 180。

public class Student { public String name; public int age; public double height; // write your code here Student(){ this.name = "Tom"; this.age = 20; this.height = 180; } }

3.2 无参构造函数的使用(二)

请根据 Main 类中对 Student 类的使用,补充 Student 的构造函数,确保程序能够顺利执行。

public class Student { String name; public Student(String name) { this.name = name; } public String toString() { return "name = " + name; } // write your code here public Student(){ this.name = null; } }

3.4 有参构造

3.5 有参构造函数的使用(一)

在 Main.java 中我们要用到 Student 类,但现在 Student 类中缺少一些构造函数,请你补充完整代码,确保程序正确执行

public class Student { public Student(String name) { this.name = name; this.age = 0; } public Student(int age) { this.age = age; } public Student(String name, int age) { this.name = name; this.age = age; } public Student() { this.age = 0; } String name; int age; public String toString() { return "name = " + name + ", age = " + age; } // write your code here }

第四章:特性

4.1 封装

4.2 编写对象属性的赋值方法和打印方法

本题我们在 Main.java 中已经写好了对 employee 对象的属性的赋值和 printInfo 方法的调用。请编写代码,实现对 employee 对象的属性的赋值方法和属性的打印方法。

public class Employee { String name; String occupation; String telephone; int age; int salary; // write your code here public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public void setTelephone(String telephone) { this.telephone = telephone; } public void setOccupation(String occupation) { this.occupation = occupation; } public void setSalary(int salary) { this.salary = salary; } public void printInfo() { System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Telephone: " + telephone); System.out.println("Occupation: " + occupation); System.out.println("Salary: " + salary); } }

4.3 求长方形的周长和面积

请在 Rectangle 类中利用 Java 中封装的知识来编写代码。
你的代码需要从标准输入流(控制台)中读入两个正整数(长方形的长和宽),通过计算然后输出长方形的周长和面积 。
本题我们在 Main.java 中已经写好了对 Rectangle 对象的创建和 Rectangle 方法的调用。
你需要在 Rectangle 类中完成对长方形的周长和面积的计算,并输出相应的值。

class Rectangle { // Write your code here private int length; private int width; public Rectangle(int len, int wid) { this.length = len; this.width = wid; } public void show() { System.out.print("周长为: " + getPerimeter() + ",面积为: " + getArea()); } private float getPerimeter() { return (length + width) * 2; } private float getArea() { return length * width; } }

4.4 继承

继承有哪些原则

  • 能够继承父类的 public 和 protected 成员变量;不能够继承父类的 private 成员变量;
  • 对于父类的包访问权限成员变量,如果子类和父类在同一个包下,则子类能够继承;否则,子类不能够继承;
  • 对于子类可以继承的父类成员变量,如果在子类中出现了同名称的成员变量,则会发生隐藏现象,即子类的成员变量会屏蔽掉父类的同名成员变量。如果要在子类中访问父类中同名成员变量,需要使用super关键字来进行引用。

4.5 打印工作内容

在抽象类 People 中声明了一个无返回类型的抽象方法 working 用于打印工作内容。现有一个 Police 类和 Chef 类都继承了 People 类。

  • 要求一:在 Police 中重写 working 方法并打印输出 The work of the police is to catch thieves.。
  • 要求二:在 Chef 中重写 working 方法并打印输出 The work of the Chef is to cook.。
  • 要求三:在 Main 中创建类 Police 的对象,变量名为 police,并调用 working 方法。
    创建类 Chef 的对象,变量名为 chef,并调用 working 方法。

Chef.java

public class Chef extends People { // write your code here public void working() { System.out.println("The work of the Chef is to cook."); } }

Main.java

public class Main { public static void main(String[] args) { // write your code here Police police = new Police(); Chef chef = new Chef(); police.working(); chef.working(); } }

Police.java

public class Police extends People { // write your code here public void working() { System.out.println("The work of the police is to catch thieves."); } }

4.6 打印牛和马的信息

请你在 Cow 类和 Horse 类的 // write your code here 处编写合适的代码,获取和设置相应属性的值。
Animal 类有 name 属性和 species 属性,和 toString 方法,其中 name 属性表示名字,species 属性表示种类,toString 方法用来返回该对象的字符串表示形式。Cow 类和 Horse 类都继承了 Animal 类的属性和方法,在 Cow 类中有 characteristics 属性,表示牛的特点,在 Horse 类中有 age 属性,表示年龄。
Cow.java

public class Cow extends Animal { private String characteristics; // write your code here public void setCharacteristics(String c){ this.characteristics = c; } private String getCharacteristics(){ return characteristics; } public String run() { return getName() + ", is a " + getSpecies() + " animal" + " he can " + getCharacteristics() + ", he is on the run!"; } }

Horse.java

public class Horse extends Animal { private int age; // write your code here public void setAge(int age){ this.age = age; } private int getAge(){ return age; } public String call() { return getName() + ", who is " + getAge() + " years old, is a " + getSpecies() + " animal, he can eat grass and run fast!"; } }

4.7 多态

4.8 鸟吃虫子

你需要在 Main.java 中的 // write your code here 处编写合适的代码,通过多态的方式打印出 “Birds eat worms”。

public class Main { public static void main(String[] args) { Animal animal = new Bird(); animal.eat(); } }

第五章:访问权限

5.1 权限修饰符

Java 中共有四个权限修饰符,分别是 private, default(表示不写), protected, public,访问权限范围由小到大。

Alt text

5.2 合理的权限

你需要合理的运用权限修饰符以及调用合适的方法,在标准输入流(控制台)中输入两个字符串,然后调用合适的方法以及选择正确的权限将字符串打印在标准输出流(控制台)中。

import other.*; public class Solution extends Other1{ String root; //Write your code here public void setRoot(){ String position1 = getProtected(); String position2 = Other2.getPublic(); this.root = position1+" "+position2; } public String getRoot(){ return root; } }

第六章:重写和重载

6.1重写和重载

重载和重写都是 Java 中多态性的不同表现,重载针对的是同一类或者继承类中的表现,而重写则是只针对继承类中的表现。

6.2 张三的自我介绍

今天是张三同学第一天进入新班级,他需要做一个简单的自我介绍,你需要在 Solution 类中使用重载对方法 Add 进行编写,帮助张三完成他的自我介绍。
请在 Solution 类的 // write your code here 下面编写你的代码。

public class Solution { // write your code here public void Add(int a,int b){ System.out.println("I am "+a+" years old,I am "+b+" cm tall"); } public void Add(String a,String b){ System.out.println("My name is "+a+b); } }

6.3 实现 Pig 类和 Dog 类的方法

在接口 Animal 中,包含两个抽象无返回值的方法 eat 和 status。类 Dog 和 Pig 都实现了 Animal 接口。

要求一:请在 Pig 文件中的 eat 方法内输出打印 Pig is eating vegetables. ,status 方法内输出打印 Pig is sleeping.。
要求二:请在 Dog 文件中的 eat 方法内输出打印 Dog is eating meat.,status 方法内输出打印 Dog is running.。
Dog.java

public class Dog implements Animal { // write your code here public void eat(){ System.out.println("Dog is eating meat."); } public void status(){ System.out.println("Dog is running."); } }

Pig.java

public class Pig implements Animal { // write your code here public void eat(){ System.out.println("Pig is eating vegetables."); } public void status(){ System.out.println("Pig is sleeping."); } }

第七章:this 关键字

7.1this 关键字\

this();

  • 访问本类的构造函数。
  • ()中可以有参数,如果有参数,就是调用指定的有参构造 。

注意事项:

  • this() 不能使用在普通方法中, 只能写在构造函数中。
  • 必须是构造函数中的第一条语句。

7.2 打印学生的个人信息

在本题中,Students 类中有 name 属性,age 属性,sex 属性和 number 属性,fun 方法,其中 name 属性表示学生的名字,age 属性表示学生的年龄,sex 属性表示学生的性别,number 属性表示学生的学号,fun 方法用来返回这些信息的表示形式。
请你在 Students 类中的 // write your code here 处编写合适的代码。

public class Students { private String name; private int age; private String sex; private int number; public Students(String name, int age, String sex, int number) { // write your code here this.name = name; this.age = age; this.sex = sex; this.number = number; } public void fun() { // write your code here System.out.println("名字:"+this.name+",年龄:"+this.age+",性别:"+this.sex+",学号:"+this.number); } }

第八章:super 关键字

8.1 我是康康

class Child extends Parent { // write your code here public Child(){ super.name(); } }

第九章:异常

9.1 异常捕获1

今天小明编写了一个除法计算器的工具类 Calculators,写完后他就发给了小红。但是细心的小红发现,在计算除法时,如果被除数是 0 时会出现错误。小红想帮小明完善他的程序,当被除数是 0 时,就抛出异常提示 The divisor cannot be 0.。

public class Solution { public String division(int a, int b) { // -- write your code here -- try{ new Calculators().calc(a,b); return "Calculated results are normal."; }catch(Exception e){ return "The divisor cannot be 0."; } } }

9.2 倒序数组

现在有一个方法 invertedArray(int n , int k) 用来创建倒序数组,倒数数组的规则如下:
数组长度为 n。
数组从 0 ~ n-1 中依次填充 k ~ 0。
在填充时,数组中的值为非负数,若 k 小于 n ,不足填充 0,若 k 大于 n 需要抛出异常信息 The length of parameter k is not legal.。

public class Solution { public int[] invertedArray(int n , int k) throws Exception { // -- write your code here -- if(k>n){ throw new Exception("The length of parameter k is not legal."); } int []arr = new int[n]; for(int i=0;i<arr.length;i++){ if(k>0){ arr[i] = k; k -= 1; }else{ arr[i] = 0; } } return arr; } }

9.3 自定义异常

在 Solution 类中有一个 checkAge(int num) 方法,这个方法用来判定 num 是否是 非百岁老人 判断标准及要求如下:

非百岁老人 是指 0 到 99 岁之间的人;
如果不是 非百岁老人 ,需要抛出一个 NoAgesException 异常,并填写异常信息 Age Error!
您需要实现 checkAge(int num) 方法,并且自定义异常处理类 NoAgesException。

NoAgesException.java

public class NoAgesException extends Exception { public NoAgesException (String str){ super(str); } }

Solution.java

public class Solution { public boolean checkAge(int num) throws Exception { // -- write your code here -- if(num>=0&&num<=99){ return true; } throw new NoAgesException("Age Error!"); } }

第十章:注解

10.1 注解

注解常见的作用有以下几种:

  • 生成帮助文档。这是最常见的,也是 Java 最早提供的注解。常用的有 @see、@param 和 @return 等;

  • 跟踪代码依赖性,实现替代配置文件功能。比较常见的是 Spring 2.5 开始的基于注解配置。作用就是减少配置。现在的框架基本都使用了这种配置来减少配置文件的数量;

  • 在编译时进行格式检查。如把 @Override 注解放在方法前,如果这个方法并不是重写了父类方法,则编译时就能检查出。

1.@Override 注解
Java 中 @Override 注解是用来指定方法重写的,只能修饰方法并且只能用于方法重写,不能修饰其它的元素。它可以强制一个子类必须重写父类方法或者实现接口的方法。

使用 @Override 注解示例代码如下:

public class Person { private String name = ""; private int age; ... @Override public String t0String() { //toString() return "Person [name=" + name + ", age=" + age + "]"; } }

上述代码第 6 行是重写 Object 类的 toString() 方法,该方法使用 @Override 注解。如果 toString() 不小心写成了 t0String(),那么程序会发生编译错误。会有如下的代码提示:

Method does not override method from its superclass

2.@Deprecated 注解
Java 中 @Deprecated 可以用来注解类、接口、成员方法和成员变量等,用于表示某个元素(类、方法等)已过时。当其他程序使用已过时的元素时,编译器将会给出警告。

使用 @Deprecated 注解示例代码如下:

@Deprecated public class Person { @Deprecated protected String name; private int age; @Deprecated public void setNameAndAge(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }

上述代码分别对类 Person、属性 name、方法setNameAndAge(String name, int age) 添加了注解 @Deprecated。在编译器中这些被注解的 API 都会被画上删除线。调用这些 API 代码也会有删除线,示例代码如下。
3.@SuppressWarnings 注解
Java 中的 @SuppressWarnings 注解指示被该注解修饰的程序元素(以及该程序元素中的所有子元素)取消显示指定的编译器警告,且会一直作用于该程序元素的所有子元素。例如,使用 @SuppressWarnings 修饰某个类取消显示某个编译器警告,同时又修饰该类里的某个方法取消显示另一个编译器警告,那么该方法将会同时取消显示这两个编译器警告。
如果你确认程序中的警告没有问题,可以不用理会。通常情况下,如果程序中使用没有泛型限制的集合将会引起编译器警告,为了避免这种编译器警告,可以使用 @SuppressWarnings 注解消除这些警告。
注解的使用有以下三种:

  • 抑制单类型的警告:@SuppressWarnings("unchecked")

  • 抑制多类型的警告:@SuppressWarnings("unchecked","rawtypes")

  • 抑制所有类型的警告:@SuppressWarnings("unchecked")

10.2 自定义注解

在日常的工作开发中,我们经常需要给一个对象中的属性赋值,现在需要您创建一个自定义注解,来帮助我们完成属性赋值。请您将 MyAnnotation 类修改成一个自定义注解,并添加属性 name(String) 和 age(int) 。

import java.lang.annotation.*; //注释加入到文档 @Documented //注解保留到什么阶段 @Retention(RetentionPolicy.RUNTIME) //指定注解用在哪些目标上 @Target({ ElementType.FIELD}) public @interface MyAnnotation { int age() ; String name(); }

10.3 元注解


__EOF__

本文作者粥粥alg
本文链接https://www.cnblogs.com/3456939606zwp/p/17893456.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   粥粥alg  阅读(81)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示