Topic: 小弟初学JAVA,希望有哪位仁义大哥赐教. (如何使用this来使构造方法覆盖?)

  Print this page

1.小弟初学JAVA,希望有哪位仁义大哥赐教. (如何使用this来使构造方法覆盖?) Copy to clipboard
Posted by: LLL_QQQ
Posted on: 2004-09-13 15:31

import java.io.*
public class Student(){
String name1,name2;
int age;

public Student(String s1,String s2 ,int n){
name1=s1;
name2=s2;
age=n;
}

public Student (String s1,String s2;){
this(s1,s2,20);
}

public Student(){
this("Unknown");
}

public static void main(String[] args){
Student s=new Student;
System.out.println(s.name1+s.name2+s.age);
}
}

如何使用this来使构造方法覆盖?(这个程序如何改?) :)

2.Re:小弟初学JAVA,希望有哪位仁义大哥赐教. (如何使用this来使构造方法覆盖?) [Re: LLL_QQQ] Copy to clipboard
Posted by: why
Posted on: 2004-09-13 17:34

Why would you think you should use this?
Can't it be

import java.io.*
public class Student(){
String name1,name2;
int age;

public Student(String s1, String s2, int n){
name1=s1;
name2=s2;
age=n;
}

public Student (String s1,String s2){
name1=s1;
name2=s2;
age=20;
}

public Student(){
name1="Unknown";
// name2=null;
// age=0;
}

public static void main(String[] args){
Student s=new Student;
System.out.println(s.name1+s.name2+s.age);
}
}

If you want to use a method to initialize the object, just add a private method to do so
private setDefault(String s1,String s2 ,int n) {
//...
}

3.Re:小弟初学JAVA,希望有哪位仁义大哥赐教. (如何使用this来使构造方法覆盖?) [Re: LLL_QQQ] Copy to clipboard
Posted by: LLL_QQQ
Posted on: 2004-09-13 18:55

非常感谢总版主!小弟清楚了
^_^

4.Re:小弟初学JAVA,希望有哪位仁义大哥赐教. (如何使用this来使构造方法覆盖?) [Re: LLL_QQQ] Copy to clipboard
Posted by: alpacino
Posted on: 2004-09-21 16:54

构造函数不能被继承,所以也不存在构造函数重置这一说

5.Re:小弟初学JAVA,希望有哪位仁义大哥赐教. (如何使用this来使构造方法覆盖?) [Re: LLL_QQQ] Copy to clipboard
Posted by: april518
Posted on: 2004-09-24 16:46

this 指代所创建的对象,未创建对象之前何来的this呢?随便说说不知道对不对,见笑见笑了!

6.Re:小弟初学JAVA,希望有哪位仁义大哥赐教. (如何使用this来使构造方法覆盖?) [Re: LLL_QQQ] Copy to clipboard
Posted by: LLL_QQQ
Posted on: 2004-09-25 02:02

谢谢大家!


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923