Student.java
学生类:
import java.util.Objects; import java.util.Scanner; public class Student { static int age; static String id, subject; static String name = "张晗"; //name="张晗" // 非法,因为在class类中,赋值操作语句只允许在成员函数中才可以 //在类中不允许出现操作性的语句 static char s = 'a'; public static String schoolName = "烟台大学"; //全局变量,如果具有: stu1.schoolname="鲁东大学",此时类内的全局变量也被修改,所以说会出错 //如果不想被修改 可变为: public static final String SchoolName = "烟台大学";//final表示不可被修改 public static void 上课() { System.out.println(name + "来上课"); } public static void chifan() { System.out.println(name + "12点才开始吃饭"); } public static void love() { Scanner cin = new Scanner(System.in); String s = cin.nextLine(); if (Objects.equals(s, "王浩然")) System.out.println("喜欢"); else System.out.println("不喜欢,滚"); } private static String School_Name = "烟台大学"; private String name1; //private 可以通过共有的函数来进行访问和修改 public static String getSchoolName() { return School_Name; } public static void setSchoolName(String n) { School_Name = n; } public static void main(String[] args) { Student stu1 = new Student(); stu1.name = "张晗"; Student stu2 = new Student(); stu2.name = "王浩然"; } }
Teacher.java
老师类:
//封装的含义: //数据+方法一体化,可以统一放在一个类里面,类似于打包 //可以通过权限来控制某个数据是否可访问,具有数据控性 //可复用 public class Teacher { static String name, course; public static void 授课() { Student stu_zhanghan = new Student(); //student 叫做类,同学类 stu_zhanghan.name = "张晗"; stu_zhanghan.上课(); //stu是对象,类似于 张晗同学,张晗同学是在同学类中的一员 Student stu_haoran = new Student(); stu_haoran.name = "张晗的老公"; stu_haoran.chifan(); } public static void love() { Student zhanghan = new Student(); zhanghan.love(); } public static void main(String[] args) { Teacher.授课(); love(); Student stu=new Student(); System.out.println("学校名字:"+stu.getSchoolName()); stu.setSchoolName("鲁东大学"); System.out.println("学校名字:"+stu.getSchoolName()); } }
标签:封装,String,继承,多态,stu,static,Student,public,name From: https://www.cnblogs.com/o-Sakurajimamai-o/p/17716594.html