package Experience;
public class Teacher {
String name;
int age;
public void act(){
System.out.println("大家好,我是田老师!");
}
}
package Experience;
public class Test {
public static void main(String[] args){
Teacher teacher=new Teacher();
teacher.name="田老师";
teacher.age=35;
System.out.println("今天"+teacher.age+"岁的"+teacher.name+"要来给我们上课!");
teacher.act();
}
}
第二种,private封装使用方法赋值
package Experience;
public class Student {
private String name;
private int age;
public void show(){
System.out.println(name+","+age);
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age){
if(age<=0){
System.out.println("年龄错误");
}else{
this.age=age;
}
}
public int getAge() {
return age;
}
}
package Experience;
public class Learn02 {
public static void main(String[] args){
Student s=new Student();
s.setName("小红");
s.setAge(24);
s.show();
System.out.println(s.getName()+"今年多少岁了:"+s.getAge());
}
}
第三种,使用构造方法的方式
package Experience;
public class Test {
public static void main(String[] args){
Teacher teacher=new Teacher("田老师",35);
System.out.println("今天"+teacher.getAge()+"岁的"+teacher.getName()+"要来给我们上课!");
teacher.act();
}
}
package Experience;
public class Teacher {
private String name;
private int age;
Teacher(String name,int age){
this.name=name;
this.age=age;
System.out.println("同学们好!");
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void act(){
System.out.println("大家好,我是田老师!");
}
}