public class Hello {
public Hello(){
System.out.println("Hello()");
}
public Hello(String str){
super();
System.out.println(str + "h");
}
public static void main(String[] args) {
new Hello();
new Hello("str ");
}
}如果不用super有区别吗?
public Hello(){
System.out.println("Hello()");
}
public Hello(String str){
super();
System.out.println(str + "h");
}
public static void main(String[] args) {
new Hello();
new Hello("str ");
}
}如果不用super有区别吗?
构造方法,此时要在子类里显示调用super
public class Parent
{
} public class Children extends Parent
{
public Children()
{
//父类没有构造函数,JVM自动添加一没有参数的构造函数 System.out.println("Children.");
}
public static void main(String[] args)
{
Children c = new Children();
}
}==================================================================================例二:
public class Parent
{
public Parent()
{
System.out.println("Parent.")
}
} public class Children extends Parent
{
public Children()
{ //不需要用super,JVM会自动调用父类默认的构造函数 System.out.println("Children.");
}
public static void main(String[] args)
{
Children c = new Children();
}
}===================================================================================例三:
public class Parent
{
public Parent(String str)
{
System.out.println(str);
}
} public class Children extends Parent
{
public Children()
{ //子类会调用父类默认的构造函数
//但因为程序员已手工定义了一有参数的构造函数
//所以JVM不会再自动定义默认的构造函数
//必须用super(参数1, ...)的方法指定父类的构造函数
super("test"); System.out.println("Children.");
}
public static void main(String[] args)
{
Children c = new Children();
}
}==================================================================================
class A {
private int i;
public A(int i) {
this.i = i;
}
}public class B extends A {
public B(int i) {
super(i);
}
}另外一种用法是当子类重写父类的方法,我想调用父类的这些被重写的方法的话,就要用到super
class A {
public void doSth() {
System.out.println("hello world");
}
}public class B{
public void doSth() {
super.doSth();
}
}
你的例子中没有类的继承关系,只有一个类Hello啊。super()的作用是调用父类的构造函数(里面的实参决定调用哪个构造函数),要放在第一句。super.方法名(或域名)的作用是调用父类的方法(或访问父类的域)。
和super类似的this()的作用是调用本类的其它构造函数,要放在第一句。this.方法名(或域名)的作用是调用本类的方法(或访问本类的域),当然此时通常省略this。
this,super后的域和方法通常是实例域或实例方法,因为this,super指代的是本类或父类对象。
public Hello(){
System.out.println("Hello()");
}
public Hello(String str){
super();
System.out.println(str + "h");
}
public static void main(String[] args) {
new Hello();
new Hello("str ");
}
}class HelloFather
{
HelloFather()
{
System.out.println( "HelloFather");
}
}
把前面的看看 再看看 这个例子 你就明白了!~