java語言基礎
類和物件
- 類的結構
[public][abstract][final]class 類名 [extends 父類][implements 介面串列]
{
屬性宣告及初始化;
方法說明及方法體;
}
- 構造方法
[修飾符] 類名 (引數串列){
//方法體
}
eg:
package eg1;
public class ld {
// 在員工類中加入構造方法
public class Employee{
//屬性宣告
String name;
int age;
double salary;
//不帶引數的構造方法
public Employee() {
name="小明";
age=32;
salary=2000;
}
//帶引數的建構式
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+"漲工資之后的工資為:"+salary);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
- 類與物件的關系
類是定義一個物件的資料和方法的藍本
物件的創建
- 創建物件
物件名=new 構造方法名(引數串列);
eg:
el=new Employee;
或者
e2=new Employee("小明",29,3000);
- 宣告并創建物件
Employee e1= new Employee();
Employee e2=new Employee("小李",29,3000);
- 物件的使用
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("姓名為:"+name+"的同學");
}
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("總成績為"+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的屬性y.a="+y.a);
System.out.println("呼叫后參考型別變數y的屬性y.a="+y.a);
}
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/18931.html
標籤:其他
