構(gòu)造方法
// 構(gòu)造方法,用于在內(nèi)存中創(chuàng)建對象
public Phone(){
System.out.println("我被構(gòu)造了");
}
//構(gòu)造方法
public Phone(double kuan,double gao,int zhong, String yanse){
width = kuan;
high = gao;
weight = zhong;
color = yanse;
}
作用:幫助開辟內(nèi)存空間,創(chuàng)建對象
特征:
1 . 沒有返回值 ;
2 . 名字要求和類名完全一致,區(qū)分大小寫;
3 . 分為有參構(gòu)造方法和無參構(gòu)造方法
3 . 1 無參構(gòu)造方法不不管是否書寫,都會存在
3 . 2 有參構(gòu)造方法學(xué)要手動編寫,參數(shù)個數(shù)都可以自定義
方法的重載
上面的三個構(gòu)造方法 == 》方法的重載
在同一個類中
方法的名字相同
參數(shù)不同
3.1 參數(shù)的個數(shù)不同
3.2 參數(shù)的類型不同
3.3 參數(shù)類型的順序不同
toString
public String toString(){
return "{"+this.weight+""+this.high+""+this.weight+""+this.color+"}";
}
作用:把對象按照人能夠理解的方式重寫
this
表示當(dāng)前對象(誰調(diào)用當(dāng)前方法,this帶是的就是誰)
public Phone(double width,double high,int weight, String color) {
this.width = width;
this.high = high;
this.weight = weight;
this.color = color;
}
Object類
所有類的父類,但凡有其他的類被創(chuàng)建,Object一定被創(chuàng)建、
Object類中有一些固有的方法,即使沒寫,其他所有的類中都會有這些方法
equals()原生的:比較的是兩個對象的地址是不是相同,一般場景
public boolean equals(Object obj) {
return (this == obj);
}
本列中以Phone為案列
public boolean equals(Object object){
if (this==object){
return true;
}
if (object instanceof Phone){
Phone temp = (Phone) object;
if (temp.width == this.width && temp.high == this.high && temp.weight == this.weight && temp.color == this.color){
return true;
}else {
return true;
}
return true;
}
toString()原生的:返回的是對象的內(nèi)存地址
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
**static ** 靜態(tài)的
可以修飾成員屬性,還可以修飾方法
被修飾的成員,類一旦創(chuàng)建,便分配了內(nèi)存空間,可以直接通過類名.方法()調(diào)用
不需要對象即可是用,但通過對象也可調(diào)用,但不推薦
沒有被修飾的成員:必須等待對象被創(chuàng)建,才擁有的獨立的內(nèi)存空間,之可以通過對象名.方法()調(diào)用
final 最終的
被final修飾的成員,值一旦被寫定,不能被輕易修改
類成員的執(zhí)行順序
public class Demo01 {
//2 普通的屬性或者代碼塊其次執(zhí)行,從上往下執(zhí)行
int size = 1;
{
size = 10;
}
//1 被static最先執(zhí)行,被修飾的從上往下執(zhí)行
static int count = 30;
static {
count = 3;
}
//3 最后執(zhí)行構(gòu)造方法
public Demo01(){
System.out.println(size);
System.out.println(count);
}
}
內(nèi)部類
和普通的成員一樣,擁有對應(yīng)的使用方式
public class Demo02 {
String name;
int age;
public void fun(){
System.out.println("普通的成員方法");
}
class Inner{
int sex;
double high;
public void fun01(){
System.out.println("內(nèi)部類中的普通方法");
}
}
}
權(quán)限管理
public default protected private
| 修飾符 | 同一類 | 同一個包 | 子類 | 所有類 |
|---|---|---|---|---|
| private | √ | |||
| default | √ | √ | ||
| protected | √ | √ | √ | |
| public | √ | √ | √ | √ |