构造方法(构造器)
package com.itheima1;
public class Test
{
public static void main(String[] args)
{
Integer age;
String name;
double height;
/*
new关键字实际在调用一个方法,即构造方法,又叫构造器
调用构造方法时,若类中未写构造方法,系统默认构造方法
可自己编写构造方法——[修饰符] 构造方法名(){}
构造方法与方法区别:
1.方法类型的返回值,
2.方法体内部不能含return,
3.构造方法名必须和类名相同。
*/
Person ppp= new Person();
System.out.println(ppp.name);
System.out.println(ppp.age);
Person mmm=new Person("zy",20,10.0);
System.out.println(mmm.name);
System.out.println(mmm.age);
}
}
package com.itheima1;
// 类中可包括构造器,属性,方法(没有明确顺序)
public class Person //人——类
{ //属性——名词
Integer age;
String name;
double height;
/*
构造方法(构造器)
调用构造器前对象已创建且初始化
调构造方法目的给对象属性赋值
*/
/*
一般保证空构造器存在,且不进行赋值操作
重载构造器,对属性赋值操作
空构造器在自己编写后不会分配
*/
public Person()
{
this.age=10;
this.name="zyy";
}
public Person(String name,Integer age,double height) //重载
/*
形参名与属性名相同,
为了表示对象属性,采用this关键字修饰,即指代对象
*/
{
this. name=name;
this. age=age;
this. height=height;
}
//方法——动词
public void eat() {
System.out.println("吃吃吃");
}
public void sleep() { System.out.println(); }
}
This关键字
package com.itheima1;
// 类中可包括构造器,属性,方法(没有明确顺序)
public class Person //类
{ //属性
Integer age;
String name;
double height;
public Person() //构造器
{ //this修饰构造器
this.age=10;
this.name="zyy";
}
public Person(String name,Integer age,double height) //重载
{ //this修饰属性
this. name=name;
this. age=age;
this. height=height;
}
//方法1
public void eat() { System.out.println("吃吃吃");}
//方法2
public void play()
{
this.eat();
//this修饰方法
//同类中方法互相调用
System.out.println("吃饭");
System.out.println("喝茶");
}
}
Static关键字
package itheima2;
public class Test {
int id;
static int sid;
public static void main(String[] args) {
Test t1=new Test();
t1.id=10;
t1.sid=10;
Test t2=new Test();
t2.id=20;
t2.sid=20;
Test t3=new Test();
t3.id=30;
t3.sid=30;
Test.sid=100;
System.out.println(Test.sid);
//直接用类名.属性名的方式访问
System.out.println(t1.id);
System.out.println(t2.id);
System.out.println(t3.id);
System.out.println(t1.sid);
System.out.println(t2.sid);
System.out.println(t3.sid);
/*
类加载时,将静态内容也加载到方法区的静态域中,静态的内容先于对象存在,被所有该类对象共享;
static总结:
在类加载时一起加载到方法区的静态域中,
先于对象存在;
访问方式:对象名.属性名 类名.属性名
static修饰属性的应用:
某些特定属性想在内存中共享,可用static修饰
属性:
静态属性——类变量
非静态属性——实例变量
*/
}
}
package itheima2;
public class demo
{
int id;
static int sid;
public void a()
{
System.out.println(id);
System.out.println(sid);
System.out.println("---a");
}
//public static都是修饰符,无先后顺序
//static先于对象存在
static public void b()
{
//a(); 静态方法中不能访问非静态方法
//System.out.println(id); 静态方法中不能访问非静态属性
//System.out.println(this.id); 静态方法中不能使用this
System.out.println(sid);
System.out.println("---b");
}
public static void main(String[] args)
{
demo d=new demo();
d.a();
//非静态方法可以用对象名.方法名调用
demo.b();
d.b();
//静态方法可以用对象名.方法名或者类名.方法名调用
}
}