package method;
class People{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void tell(){
System.out.println(getName());
}
}
public class method {
public static void main(String[] args) {
People per=new People();
per.setName("张三");
per.tell();
}
}
07.构造方法与重载
package method;
class WuMingFen{
String theMa,s;
int quantity;
boolean likeSoup;
public WuMingFen(String theMa,int quantity,boolean likeSoup){
this.theMa = theMa;
this.quantity = quantity;
this.likeSoup = likeSoup;
}
public WuMingFen(String theMa,int quantity){//方法的重载
this.theMa = theMa;
this.quantity = quantity;
}
public void check(){
if(likeSoup){
s="是";}
else {s="否";}
System.out.println("面码:" + theMa + " " + quantity + "两" + " " + "是否带汤:" + s);
}
}
public class demo {
public static void main(String[] args) {
WuMingFen f1 = new WuMingFen("牛肉",3,true);
f1.check();
WuMingFen f2 = new WuMingFen("酸辣",2);
f2.check();
WuMingFen f3 = new WuMingFen("酸辣",2,true);
f3.check();
}
}
14.Static关键字与普通变量的区别:创建一个名称为StaticDemo的类,并声明一个静态变量和一个普通变量。对变量分别赋予10和5的初始值。在main()方法中输出变量值。
package method;
class StaticDemo{
static int a;
int b;
public void tell(){
System.out.println(a +" "+ b);
}
}
public class demo1 {
public static void main(String[] args) {
StaticDemo str=new StaticDemo();
StaticDemo.a=10;
str.b=5;
str.tell();
}
}
03.类的成员变量与方法、构造方法在程序中,经常要对时间进行操作,但是并没有时间类型的数据。那么,我们可以自己实现一个时间类,来满足程序中的需要。定义名为MyTime的类,其中应有三个整型成员:时(hour),分(minute),秒(second),为了保证数据的安全性,这三个成员变量应声明为私有。为MyTime类定义构造方法,以方便创建对象时初始化成员变量。
再定义diaplay方法,用于将时间信息打印出来。
11.构造方法与重载将上次练习题三中编写的MyTime类打到以自己名字的拼音命名的包中,并为该类重载一组构造方法,以方便使用者能够以多种形式初始化该类的实例。
package xianweifu;
class MyTime{
private int hour,minute,second;
public MyTime(int hour,int minute,int second){
this.hour = hour;
this.minute = minute;
this.second = second;
}
public MyTime(int minute,int second){
this.minute = minute;
this.second = second;
}
public int getHour() {
return hour;
}
public void setHour(int hour) {
this.hour = hour;
}
public int getMinute() {
return minute;
}
public void setMinute(int minute) {
this.minute = minute;
}
public int getSecond() {
return second;
}
public void setSecond(int second) {
this.second = second;
}
public void display(){
if(0<=hour & hour<24 & 0<=second & second<60 & 0<=minute & minute<60){
System.out.println(getHour() + "时" + getMinute()
+ "分" + getSecond() + "秒");}
else{
System.out.println("数据错误");
}
}
}
public class time {
public static void main(String[] args) {
MyTime when=new MyTime(23,3,56);
//when.setHour(12);
//when.setMinute(3);
//when.setSecond(56);
when.display();
}
}