标签:返回 参数 style 初始化 return str generated 默认 turn
JAVA:
1 package object1; 2 3 public class Student { 4 //属性 (四种访问权限的属性) 5 public String name; 6 protected String sno; 7 int score; 8 private int age; 9 10 //注意点:1不能写返回类型 2 方法名为类名。 结构为 public 类名([参数]){}; 11 public Student(String name,String sno) { 12 //初始化属性 13 this.name = name; 14 this.sno = sno; 15 } 16 /* 17 * 方法重载(构造方法也可以重载) 1方法名相同 2返回类型、参数类型/个数不能全部相同 18 */ 19 public Student(){ 20 //调用另一个构造函数(方法) 21 this("缺省","20190123"); 22 /* 初始化属性 23 name = "B"; */ 24 } 25 public void Study() 26 { 27 System.out.println(name + "正在学习..."); 28 } 29 protected void Study(String sno,String name) 30 { 31 32 System.out.println(name + "的学号时是:"+sno); 33 } 34 public Student object() { 35 return this; 36 } 37 }
主类
1 package object1; 2 3 public class Main { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 Student stu1 = new Student("abc","123"); 8 Student stu3; 9 System.out.println("用无参构造函数生成对象stu1: \n"); 10 stu1.Study(); 11 stu1.Study("201901", "abc"); 12 13 System.out.println(); 14 Student stu2 = new Student("ABC","20190123"); 15 System.out.println("用有参构造函数生成对象stu2: \n"); 16 stu2.Study(); 17 stu2.Study("201923", "A"); 18 19 /* //对属性的使用 20 stu1.name = "B"; 21 stu1.sno = "90120123"; 22 stu1.score = 100; 23 //报错,因为age是私有属性,不能被其他类直接调用 24 stu1.age = 18; */ 25 stu3 = stu1.object(); 26 stu3.Study(); 27 stu3.name = "bvjkbsd"; 28 System.out.println(stu3.name); 29 } 30 31 }
运行结果
用无参构造函数生成对象stu1: abc正在学习... abc的学号时是:201901 用有参构造函数生成对象stu2: ABC正在学习... A的学号时是:201923 stu3: abc正在学习... bvjkbsd
Java -- 构造函数 & this & 方法重写和方法重载的区别
标签:返回 参数 style 初始化 return str generated 默认 turn
原文地址:https://www.cnblogs.com/liu1234/p/10310718.html