本文主要是介绍JAVA入门——构造函数赋值问题,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
public class student {
String name; // 不能有private
int age;
student(){
} // 不可缺少
student(String name,int age){
this.name =name; // 可有可无
this.age = age;
}
// 无get()set()
public void show() {
System.out.println("学生爱学习");
}
}
public class Teacher {
private String name; // private可有可无
private int age;
public Teacher(){
} // 必有空参,不可缺少
public Teacher(String name,int age){
this.name = name; // 可有可无
this.age = age;
}
// 用set赋值 必有get()set()
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void show(){
System.out.println("老师爱讲课");
}
}
public class xiaozhang {
private String name; // 可有可无
private int age;
public xiaozhang() {
} // 必有空参,不可缺少
public xiaozhang(String name, int age) {
this.name = name; // 必有this.变量
this.age = age;
System.out.println(name); // 若无set()get(),则必有输出sout
System.out.println(age); // 若有set get,则test中必有System.out.println(xz.getName());
System.out.println("校长爱转圈");
}
}
/* public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;*/
public class practice {
public static void main(String[] args) {
// 直接赋值,不能有private
student stu = new student();
stu.name = "小明";
stu.age = 15;
System.out.println(stu.name);
System.out.println(stu.age);
stu.show(); // 对象名调用函数
System.out.println("————————");
//用set() get()赋值
Teacher t = new Teacher();
t.setName("李老师");
t.setAge(45);
System.out.println(t.getName()); // 用set赋值用get接收
System.out.println(t.getAge());
t.show();
System.out.println("————————");
//用构造函数赋值
xiaozhang xz = new xiaozhang("张校长",60);
//System.out.println(xz.getName());
//System.out.println(xz.getAge());
这篇关于JAVA入门——构造函数赋值问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!