0
点赞
收藏
分享

微信扫一扫

Java-类和对象解析(超详细)

elvinyang 2022-03-31 阅读 33

Java语言的基本元素:类和对象

前言

本博主将用CSDN记录软件开发求学之路上亲身所得与所学的心得与知识,有兴趣的小伙伴可以关注博主!
也许一个人独行,可以走的很快,但是一群人结伴而行,才能走的更远!让我们在成长的道路上互相学习,欢迎关注!


关注并私信博主,可领JDK1.8中文版!


一、类和对象

1. 概述

例子:
在这里插入图片描述

2. 类的成员

3. 类的语法格式

3.1 常见的语法格式:

修饰符 class 类名 {
      属性声明;
      构造器;
      方法声明; 
}

3.2 例子:

public class Person{
   private int age ; //声明私有变量 age
   public void showAge(int i) { //声明方法showAge( )
   age = i; 
   } 
}

4. 对象的创建和使用

在这里插入图片描述

4.1 对象的创建:

4.2 对象的使用:

代码演示:

演示1public class Zoo{
        public static void main(String args[]){        
         Animal xb=new Animal(); //创建对象
         xb.legs=4;//访问属性
         System.out.println(xb.legs);
         xb.eat();//访问方法
         xb.move();//访问方法
       }
}
   
class Animal {
      public int legs;
      public void eat(){
       System.out.println(Eating.);
      }
      public viod move(){
       System.out.println(Move.);
      }
}
演示2class Person{
   int age;
   void shout(){
      System.out.println(“oh,my god! I am ” + age);
   }
}

在这里插入图片描述

在这里插入图片描述

代码演示:

public class Zoo {
     public static void main(String args[]) {
           Animal xb = new Animal();
           Animal xh = new Animal();
           xb.legs = 4;
           xh.legs = 0;
           System.out.println(xb.legs); // 4
           System.out.println(xh.legs); // 0
           xb.legs = 2;
           System.out.println(xb.legs); // 2
           System.out.println(xh.legs); // 0
      } 
}

5. 对象的生命周期

在这里插入图片描述
在这里插入图片描述

6. 对象的内存解析

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

7. 匿名对象的创建

(1)概念

(2)理解

(3)特征

(4)使用情况

(5)代码演示

public class InstanceTest {
	public static void main(String[] args) {	
		//匿名对象
//		new Phone().sendEmail();
//		new Phone().playGame();
		
		new Phone().price = 1999;
		new Phone().showPrice();//0.0
		
		//**********************************
		PhoneMall mall = new PhoneMall();
//		mall.show(p);
		//匿名对象的使用
		mall.show(new Phone());		
	}
}


class PhoneMall{	
	public void show(Phone phone){
		phone.sendEmail();
		phone.playGame();
	}	
}


class Phone{
	double price;//价格	
	public void sendEmail(){
		System.out.println("发送邮件");
	}	
	public void playGame(){
		System.out.println("玩游戏");
	}	
	public void showPrice(){
		System.out.println("手机价格为:" + price);
	}	
}

二、类的成员之一:属性(field)

1. 语法格式

(1)修饰符

(2)数据类型

(3)属性名

//举例:
    public class Person{
       private int age; //声明private变量 age
       public String name =Lila; //声明public变量 name
}

2. 成员变量(属性)vs 局部变量

2.1 定义

在这里插入图片描述

2.2 相同点

2.3 不同点

(1)在类中声明的位置的不同

代码演示:

public class UserTest {	
	public static void main(String[] args) {
		User u1 = new User();
		System.out.println(u1.name);
		System.out.println(u1.age);
		System.out.println(u1.isMale);		
		u1.talk("韩语");		
		u1.eat();		
	}
}


class User{
	//属性(或成员变量)
	String name;
	public int age;
	boolean isMale;	
	public void talk(String language){//language:形参,也是局部变量
		System.out.println("我们使用" + language + "进行交流");		
	}	
	public void eat(){
		String food = "烙饼";//局部变量
		System.out.println("北方人喜欢吃:" + food);
	}	
}

(2) 关于权限修饰符的不同

(3) 默认初始化值的情况

数组元素类型元素默认初始值
byte0
short0
int0
long0L
float0.0F
double0.0
char0 或写为:’\u0000’(表现为空)
booleanfalse
引用类型null

(4) 在内存中加载的位置不同

在这里插入图片描述

总结:

成员变量局部变量
声明的位置直接声明在类中方法形参或内部、代码块内、构造器内等
修饰符private、public、static、final等不能用权限修饰符修饰,可以用final修饰
初始化值有默认初始化值没有默认初始化值,必须显式赋值,方可使用
内存加载位置堆空间 或 静态域内栈空间

3. 属性赋值的先后顺序

4. 注意

代码演示:

class Window {
     Window(int marker) { print("Window(" + marker + ")"); }
class House {
     Window wl = new Window(1); // Before constructor
     House(){
     // Show that we're in the constructor: printCHouseO");
     w3 = new Window(33): // Reinitialize w3
     }
     Window w2 = new Window(2); // After constructor
     void f() { prlnt("f()"); )
     Window w3 = new Window(3): // At end
}
public class OrderOfInitialization {
     public static void main(String[] args) {
     House h = new HouseO ;
     h.f(); // Shows that construction 1s done
     }
} 
/* Output:
Window(l)
Window(2)
W1ndow(3)
House()
Window(33)
f()
*/
/*解析:
在House类中,故意把几个Window对象的定义散布到各处,以证明它们全都会在调用构造器或其他方法之前得到初始化。
此外,w3在构造器内再次被初始化。由输出可见,w3这个引用会被初始化两次:一次在调用构造器前,一次在调用期间
(第一次引用的对象将被丢弃,并作为垃圾回收)。
*/

三、类的成员之二:方法(method)

1.初步了解“方法”

1.1 定义

1.2 语法格式

(1) 权限修饰符

(2) 返回值类型

代码演示:

 public void test1(){}//无返回值
 public void test2(){ return;}//无返回值
 public int test3(){ return 0;}//有返回值(以int为例)

(3)方法名

(4) 形参列表

代码演示:

public void test1(){}
public void test2(int i1){}
public void test3(int i1,int i2){}
...

(5) 方法体

方法的分类:按照是否有形参及返回值
在这里插入图片描述

1.3 举例

  public void eat(){}
  public void sleep(int hour){}
  public String getName(){}
  public String getNation(String nation){}
  Math类:sqrt()\random() \...
  Scanner类:nextXxx() ...
  Arrays类:sort() \ binarySearch() \ toString() \ equals() \ ...

1.4 注意

1.5 方法参数的值传递机制

代码演示:

public class ValueTransferTest1 {
	public static void main(String[] args) {		
		int m = 10;
		int n = 20;		
		System.out.println("m = " + m + ", n = " + n);//m = 10, n = 20	
		ValueTransferTest1 test = new ValueTransferTest1();
		//交换的错误操作:
		test.swap(m, n);	
		
		//交换的正确操作:
//		int temp = m ;
//		m = n;
//		n = temp;	

		System.out.println("m = " + m + ", n = " + n);// m = 10, n = 20
	}
		
	public void swap(int m,int n){
		int temp = m ;
		m = n;
		n = temp;
	}
}

代码演示:

public class ValueTransferTest2 {	
	public static void main(String[] args) {		
		Data data = new Data();		
		data.m = 10;
		data.n = 20;
		
		System.out.println("m = " + data.m + ", n = " + data.n);
		
		//交换m和n的值
//		int temp = data.m;
//		data.m = data.n;
//		data.n = temp;
		
		ValueTransferTest2 test = new ValueTransferTest2();
		test.swap(data);				
		System.out.println("m = " + data.m + ", n = " + data.n);		
	}	
	public void swap(Data data){
		int temp = data.m;
		data.m = data.n;
		data.n = temp;
	}
}

class Data{	
	int m;
	int n;	
}

参数类型为引用数据类型的内存解析:

在这里插入图片描述

2.方法的重载(overload)

2.1 定义

代码演示:

public void test1(int i1){}
public void test1(int i1,int i2){}
public void test1(String i1){}
//以上三个test1()相互构成重载
public void test2(int i,String s){}
public void test2(String s,int i){}
以上两个test2()相互构成重载

2.2 举例

2.3 如何判断是否是重载?

2.4 如何确定某一个指定的方法?

代码演示:

public class Test1 {
    static void f(String s,int i){
        System.out.print("String: "+s+", int: "+i);
    }
    static void f(int i,String s){
        System.out.print("int: "+i+", String: "+s);
    }
    public static void main(String args[]){
        f("String first",11);
        System.out.println();
        f(99,"Int first");
    }
}
//output:
//String: String first, int: 11
//int: 99, String: Int first
//上例中两个print()方法虽然声明了相同的参数,但顺序不同,因此得以区分

2.5 关于“可变个数形参”的方法

代码演示:

       public static void test(int a ,String[] books);//JDK 5.0以前
       public static void test(int a ,String…books);//JDK5.0之后

代码演示:

	public void show(String ... strs){ }

代码演示:

	public void show(String ... strs){	}
//	public void show(String[] strs){ } 不能与上一个方法同时存在

代码演示:

//	public void show(String ...strs,int i){ }
// 报错:The variable argument type String of the method show must be the last parameter

代码演示:

// public void show(String ...str1,String ...str2){ }

2.6 注意

3.方法的重写(override / overwrite)

3.1 定义

代码演示:

public class Person {
   String name;
   int age;
   int sex;
   public void study(){
    System.out.println("studying");
   }
}
public class Student extends Person {
   //对父类中的study()进行重写
   public void study(){
    System.out.println("骑自行车");
   }
}

3.2 应用

3.3 使用
语法格式:

权限修饰符 返回值类型 方法名(形参列表) throws 异常的类型{
		//方法体
}

(1)方法名与形参列表

(2)权限修饰符

(3)返回值类型

(4)异常类型

代码演示:

public class A {
      public void methodA() throws IOException {
        ……
      } 
}
public class B1 extends A {
      public void methodA() throws FileNotFoundException {
      ……
      } 
}
public class B2 extends A {
      public void methodA() throws Exception { //报错
      ……
      } 
}

(5)static/非static

四、类的成员之三:构造器

1. 作用

代码演示:

    Order o = new Order(); 
    Person p = new Person(Peter,15);

2. 特征

代码演示:

class Person{
	//构造器
	public Person(){
		System.out.println("Person().....");
	}
	
	public Person(String n){
		name = n;
		
	}
	
	public Person(String n,int a){
		name = n;
		age = a;
	}
}	

3.构造器的重载

代码演示:

     //构造器重载举例:
     public class Person{
          public Person(String name, int age, Date d) {this(name,age);}
          public Person(String name, int age) {}
          public Person(String name, Date d) {}
          public Person(){}
} 

五、类的成员之四:代码块

1. 作用

2. 分类

2.1 静态代码块:用static 修饰的代码块

代码演示:

class Person {
    public static int total;
      static {
        total = 100;//为total赋初值
      }
      …… //其它属性或方法声明
}

2.2 非静态代码块:没有static修饰的代码块

代码演示:

class Mug {
    Mug(int marker) {
        System.out.print("Mug(" + marker + ")");
    }
    void f(int marker) {
        System.out.print ("f(" + marker + ")");
    } 
}
public class Mugs {
    Mug mugl;
    Mug mug2;
    {
        mugl = new Mug(l);
        mug2 = new Mug(2);
        System.out.print("mugl & mug2 Initialized");
    }
    Mugs() {
        System.out.print("Mugs()");
    }
    
    Mugs(int i) {
        System.out.print("Mugs(int)");
    }
    public static void main(String[] args) {
        System.out.print("Inside main()");
        new Mugs();
        System.out.print("new Mugs() completed");
        new Mugs(l);
        System.out.print("new Mugs(l) completed");
    }
} 
/* Output:
Inside main()
Mug(l)
Mug(2)
mugl & mug2 initialized
Mugs()
new MugsO completed
Mug(l)
Mug(2)
mugl & mug2 initialized
Mugs(int)
new Mugs(l) completed
*/

3. 举例

代码演示:

public class BlockTest {
	public static void main(String[] args) {		
		String desc = Person.desc;
		//hello,static block-2
		//hello,static block-1
		//我是一个快乐的人!
		System.out.println(desc);//我是一个爱学习的人				
		Person p1 = new Person();
		//hello, block - 2
		//hello, block - 1
		//吃饭
		//我是一个快乐的人!
		Person p2 = new Person();
		//hello, block - 2
		//hello, block - 1
		//吃饭
		//我是一个快乐的人!
		System.out.println(p1.age);//1		
		Person.info();//我是一个快乐的人!
	}
}


class Person{
	//属性
	String name;	
	int age;
	static String desc = "我是一个人";	
	//构造器
	public Person(){		
	}
	public Person(String name,int age){
		this.name = name;
		this.age = age;
	}	
	//非static的代码块
	{
		System.out.println("hello, block - 2");
	}
	{
		System.out.println("hello, block - 1");
		//调用非静态结构
		age = 1;
		eat();
		//调用静态结构
		desc = "我是一个爱学习的人1";
		info();
	}
	//static的代码块
	static{
		System.out.println("hello,static block-2");
	}
	static{
		System.out.println("hello,static block-1");
		//调用静态结构
		desc = "我是一个爱学习的人";
		info();
		//不可以调用非静态结构
//		eat();
//		name = "Tom";
	}	
	//方法
	public void eat(){
		System.out.println("吃饭");
	}
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
	public static void info(){
		System.out.println("我是一个快乐的人!");
	}	
}

六、类的成员之五:内部类

1. 引入

2. 理解

3. 分类

3.1 成员内部类(static成员内部类和非static成员内部类)
成员内部类作为类的成员的角色:

成员内部类作为类的角色:

注意:

举例:

代码演示:

//举例一:
class Outer {
    private int s;
    public class Inner {
      public void mb() {
        s = 100;
        System.out.println("在内部类Inner中s=" + s);
      } 
    }
    public void ma() {
       Inner i = new Inner();
       i.mb();
     } 
    }
public class InnerTest {
    public static void main(String args[]) {
       Outer o = new Outer();
       o.ma();
    } 
}

//举例二:

```java
public class Outer {
    private int s = 111;
    public class Inner {
        private int s = 222;
        public void mb(int s) {
            System.out.println(s); // 局部变量s
            System.out.println(this.s); // 内部类对象的属性s
            System.out.println(Outer.this.s); // 外部类对象属性s 
        } 
    }
    public static void main (String args[]){
        Outer a = new Outer();
        Outer.Inner b = a.new Inner();
        b.mb(333);
    }
}

3.2 局部内部类(不谈修饰符)
(1)语法格式

class 外部类{
		方法(){
			class 局部内部类{ } 
		}
		{
		    class 局部内部类{ } 
		}
} 

(2)使用

代码演示:

//返回一个实现了Comparable接口的类的对象
	public Comparable getComparable(){
		
		//创建一个实现了Comparable接口的类:局部内部类
		//方式一:
//		class MyComparable implements Comparable{
//
//			@Override
//			public int compareTo(Object o) {
//				return 0;
//			}
//			
//		}
//		
//		return new MyComparable();		
		//方式二:
		return new Comparable(){
			@Override
			public int compareTo(Object o) {
				return 0;
			}			
		};		
	}

代码演示:

public void method(){
		//局部变量
		int num = 10;		
		class AA{						
			public void show(){
//				num =20;
				System.out.println(num);				
			}						
		}				
	}	

(3)特点

3.3 匿名内部类
(1) 语法格式

 new 父类构造器(实参列表)|实现接口(){
//匿名内部类的类体部分
} 

(2)特点

代码演示:

interface A{
   public abstract void fun1();
}
public class Outer{
    public static void main(String[] args) {
      new Outer().callInner(new A(){
//接口是不能new但此处比较特殊是子类对象实现接口,只不过没有为对象取名
        public void fun1() {
           System.out.println(“implement for fun1");
        }
      );// 两步写成一步了
      }
      public void callInner(A a) {
        a.fun1();
      }
}

4. 使用

代码演示:

public class InnerClassTest {
	public static void main(String[] args) {		
		//创建Dog实例(静态的成员内部类):
		Person.Dog dog = new Person.Dog();
		dog.show();
		//创建Bird实例(非静态的成员内部类):
//		Person.Bird bird = new Person.Bird();//错误的
		Person p = new Person();
		Person.Bird bird = p.new Bird();
		bird.sing();		
		System.out.println();		
		bird.display("黄鹂");		
	}
}

class Person{
	String name = "小明";
	int age;	
	public void eat(){
		System.out.println("人:吃饭");
	}		
	//静态成员内部类
	static class Dog{
		String name;
		int age;		
		public void show(){
			System.out.println("卡拉是条狗");
//			eat();
		}		
	}
	//非静态成员内部类
	class Bird{
		String name = "杜鹃";		
		public Bird(){			
		}		
		public void sing(){
			System.out.println("我是一只小小鸟");
			Person.this.eat();//调用外部类的非静态属性
			eat();
			System.out.println(age);
		}		
		public void display(String name){
			System.out.println(name);//方法的形参
			System.out.println(this.name);//内部类的属性
			System.out.println(Person.this.name);//外部类的属性
		}
	}		
	public void method(){
		//局部内部类
		class AA{
			
		}
	}	
	{
		//局部内部类
		class BB{			
		}
	}
	
	public Person(){
		//局部内部类
		class CC{			
		}
	}			
}
举报

相关推荐

java-类和对象

Java-类与对象

Java-对象与类-总结

java-对象转换

Java-面向对象

Java-接口和抽象类

Java-抽象类和抽象方法

0 条评论