學習日志——2019/07/05
發表時(shí)間:2019-7-5
發布人(rén):融晨科技
浏覽次數:50
java語言基礎
類和(hé / huò)對象
- 類的(de)結構
[public][abstract][final]class 類名 [extends 父類][implements 接口列表]
{
屬性聲明及初始化;
方法說(shuō)明及方法體;
}
- 構造方法
[修飾符] 類名 (參數列表){
//方法體
}
eg:
package eg1;
public class ld {
// 在(zài)員工類中加入構造方法
public class Employee{
//屬性聲明
String name;
int age;
double salary;
//不(bù)帶參數的(de)構造方法
public Employee() {
name="小明";
age=32;
salary=2000;
}
//帶參數的(de)構造函數
public Employee(String n,int a,double s){
name=n;
age=a;
salary=s;
}
void raise(double p) {
salary =salary+p;
System.out.println(name+"漲工資之(zhī)後的(de)工資爲(wéi / wèi):"+salary);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
- 類與對象的(de)關系
類是(shì)定義一個(gè)對象的(de)數據和(hé / huò)方法的(de)藍本
對象的(de)創建
- 創建對象
對象名=new 構造方法名(參數列表);
eg:
el=new Employee;
或者
e2=new Employee("小明",29,3000);
- 聲明并創建對象
Employee e1= new Employee();
Employee e2=new Employee("小李",29,3000);
- 對象的(de)使用
eg:
package e;
public class Student {
String name;
int pingshi;
int qimo;
Student(String n,int p,int q){
name=n;
pingshi=p;
qimo=q;
}
void print() {
System.out.println("姓名爲(wéi / wèi):"+name+"的(de)同學");
}
double jisuan() {
return pingshi+qimo*0.5;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Student s1;
s1=new Student("王明",30,80);
s1.print();
System.out.println("總成績爲(wéi / wèi)"+s1.jisuan());
}
}
- 給方法傳遞對象參數
package eg1;
class A{
int a;
public A() {
a=1;
}
public void add(int m,A n) {
m++;
n.a++;
}
}
public class TestpassObject {
public static void main(String[] args) {
// TODO Auto-generated method stub
int x=5;
A y=new A();
System.out.println("調用前簡單類型變量x="+x);
System.out.println("調用前引用類型變量y的(de)屬性y.a="+y.a);
System.out.println("調用後引用類型變量y的(de)屬性y.a="+y.a);
}
}