类和对象
1. 对象的定义
对象是类的实例化
对象的声明:类名对象名 = new类名();
Vehicle car =new Vehicle();
2.类的定义
类是可以用来描述具有相同字段和行为的对象的集合
定义:
Class<类名>{
<类主体>//可以在这添加注释
}
/**
*欢迎类
*@author Administrator
*
**/
publicclass HellowWord {
/**
*入口方法
*@param args
* */
publicstaticvoid main(String[] args){
System.out.println("Hello Wrold!!");
System.out.println("您好!我是微软IT学员!");
System.out.println("姓名:aibc");
System.out.println("年龄:20");
System.out.println("爱好:打篮球,田径");
/*
* 带格式描述的数据输出
*/
System.out.printf("格式化为整数:%d",22);
System.out.printf("%n格式化为3位浮点数:%.3f", Math.PI);
System.out.printf("%n格式化为科学计数:%2e",1500.33);
System.out.printf("%n格式化为十六进制数:%x", 16);
System.out.printf("%n格式化为字符串:%s", 123);
}
}
3.Finally关键字的使用
import javax.swing.JOptionPane;//导入对话框类
publicclass HelloMane {
//final 修饰的变量称之为 常量(不可更改的变量)
finaldoublePI = 3.14;
finalintm = 12;//在有些情况下 变量数值固定 需要用finally
staticintnum =3;
publicstaticvoid main(String[] args){
//PI = 2321;
//对话框提示输入 并把输入存储到字符串变量中
Stringresult = JOptionPane.showInputDialog(null,"请输入姓名:");
//字符串输出
System.out.println("你输入的姓名是:"+result);
//对话框输出
JOptionPane.showMessageDialog(null,"你好:"+result+"!");
}
}
4.私有类和公共类
//私有类 只能在文件内
class Person{
Stringname;
intage;
void talk(){
System.out.println("我是:"+name+",今年:"+age+"岁");
}
}
//一个文件只能有一个类是公共类
publicclass Textperson {
publicstaticvoid main(String[] args){
Personp = new Person();
p.name="张三丰";
p.age=120;
p.talk();
}
}
5.类的方法定义
/**
*交通工具类
*@author Administrator
**/
publicclass Vehicle {
public Stringv_name;//名字
public Stringtype;//类型
/**
*运行方法
*/
publicvoid run(){
System.out.println(v_name+":"+type+"正在运行!");
}
/**
* 停止方法
*/
publicvoid stop(){
System.out.println(v_name+":"+type+"停止!");
}
}
6.测试类
/**
*测试类
*@author Administrator
**/
publicclass Text {
publicstaticvoid main(String[] args){
Vehiclecar = new Vehicle();//声明汽车对象
car.v_name="奥迪A6";
car.type="汽车";
car.run();
car.stop();
Vehiclehc = new Vehicle();
hc.v_name="和谐号";
hc.type="火车";
hc.run();
hc.stop();
}
}
7.图形界面
import javax.swing.JOptionPane;//导入对话框类
/**
*我的第一个图形界面
*@author Administrator
*
**/
publicclass FirstDialog {
/**
* 入口方法
* @param args
* **/
publicstaticvoid main(String[] args){
//单行注释
JOptionPane.showMessageDialog(null,"我的第一个图形界面!");
/*
* 多行注释
*/
System.out.println((8*4*2+6)/2+4);
}
}