//作业
public class Main {
public static void main(String[] args) {
int week = 5;
switch (week) {
case 1:
System.out.println("星期一");
break;
case 2:
System.out.println("星期二");
break;
case 3:
System.out.println("星期三");
break;
case 4:
System.out.println("星期四");
break;
case 5:
System.out.println("星期五");
break;
case 6:
System.out.println("星期六");
break;
case 7:
System.out.println("星期天");
break;
}
}
}
方法
import java.util.Scanner;
public class Main{
public static void main(String[] args){
print1();
}
public static void print1()
{
System.out.println("nihao");
}
//一个方法不能定义到另一个里面,所以这个不能放在上一个那里面
}
类
class student {
String name;
int id;
//类类似于结构体,结构体就在内部定义其读取方式;
void read() {
System.out.println("你好我是" + name);
}
public class Main {
public static void main(String[] args) {
student st1 = new student();
st1.name = "xiaoqiqi";
st1.id = 1;
st1.read();
}
}
}
封装
//实现封装
//实现封装
class Student {
private String name;
private int age;
//实例变量
//只能通过类内部student访问,而外部类必须通过公开的方法getname,setname访问;
public String getName() {
return name;
}
//局部变量是在方法或构造函数内部定义的变量
public void setName(String name) {
this.name = name;
/*
将方法参数 name 的值赋给实例变量 this.name。
也就是说,它将传入的值更新到对象的属性中。
*/
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age < 0) {
System.out.println("您输入的年龄有误");
} else {
this.age = age;
}
}
public void read() {
System.out.println("大家好,我是" + name + "年龄" + age);
}
}
public class Main {
public static void main(String[] args) {
Student stu = new Student();
stu.setName("xiaoqiqi");
stu.setAge(-18);
stu.read();
}
}
构造方法的重载
//实现封装
class Student {
private String name;
private int age;
public Student() {
}
//无参构造函数
public Student(String n) {
name = n;
System.out.println("调用了一个参数构造方法");
}
public Student(String n, int a) {
name = n;
age = a;
System.out.println("调用了两个参数的构造方法");
}
public void read() {
System.out.println("大家好,我是" + name + "年龄" + age);
}
}
public class Main {
public static void main(String[] args) {
Student stu1 = new Student("xiaoqiqi");
Student stu2 = new Student("xiaoqiqqi", 1);
stu1.read();
stu2.read();
}
}