Java面向对象基础就包括有参构造方法和成员方法
无参构造声明方式为
class Teacher{//无参构造方法,一般用在初始化变量 public Teacher(){ }}
有参构造声明为
class Teacher{//有参构造方法,一般用在设置变量值 String name; public Teacher(String name){ this.name = name; }
接下来放两个例子,分别为有参构造,成员方法使用(成员方法就不讲了,太过于好理解)
1、有参构造实例
public class Main { public static void main(String[] args) { // TODO 自动生成的方法存根 Teacher teacher = new Teacher("王老师",17,"S1班","篮球"); teacher.sayInfo(); System.out.println("----------------"); Teacher teacher2 = new Teacher("李老师",18,"S2班","足球"); teacher2.sayInfo(); }}class Teacher{ String name; int age; String jiudu; String aihao; public Teacher(String name,int age,String jiudu,String aihao){ this.name = name; this.age = age; this.jiudu = jiudu; this.aihao = aihao; } public void sayInfo() { System.out.printf("%s\n年龄:%d\n就读于:%s\n爱好:%s\n", name,age,jiudu,aihao); }}
2、成员方法实例
public class Main { public static void main(String[] args) { // TODO 自动生成的方法存根 Menpiao menpiao = new Menpiao(); menpiao.setName("张三"); menpiao.setAge(17); menpiao.pay(); }}class Menpiao { // 成员属性声明 String name; int age; String money; //设置成员名称 public void setName(String name) { this.name = name; } //设置成员年龄 public void setAge(int age) { this.age = age; if (age > 16) { this.money = "20"; } else { this.money = "免费"; } } // 支付,打印小票 public void pay() { System.out.printf("%s的年龄为:%d,门票价格为:%s",name,age,money); }}