Java-构造方法总结

在这里插入图片描述
在这里插入图片描述

public class Student {
    
    
	public Student() {
    
    
		System.out.println("构造方法在这里");
	}
}
public class ssss {
    
    
	public static void main(String[] args) {
    
    
		Student stu =new Student();		
	}
	
}

在这里插入图片描述当没写构造方法的时候,会默认一个构造方法,但是没有输出的东西,所以创建对象的时候,运行,没有输出
当写了构造后,创建对象的时候时候,运行,会有输出。


当构造方法中有参数的时候

public class Student {
    
    
	//私有变量	
	private String name;
	//带参数的构造方法
	public Student( String name) {
    
    
		System.out.println("构造方法运行了");
		this.name=name;
	}
	//设置
	public void setName(String str) {
    
    
		this.name=str;
		
	}
	//得到
	public String getName() {
    
    
		return this.name;
	}
}

对象中

public class ssss {
    
    
	public static void main(String[] args) {
    
    
		Student stu =new Student("小学生");
		System.out.println("我叫"+stu.getName());
	}
	
}

在这里插入图片描述

这样,构造方法中带参数的时候,有私有变量时,对象中不用再setName的值了。
但是想修改参数值的时候,还需要setName

public class ssss {
    
    
	public static void main(String[] args) {
    
    
		Student stu =new Student("小学生");
		System.out.println("我叫"+stu.getName());
		stu.setName("小青蛙");
		System.out.println("我叫"+stu.getName());		
	}		
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/QL_DIANDIAN/article/details/108698617
今日推荐