构造器:
构造器也叫构造方法,无返回值。非构造方法必须要有返回类型
主要作用:完成对象的初始化,创造对象时,自动调用构造器初始化对象
即使没有显示地使用static关键字,构造器实际上也是静态方法
JAVA中静态的东西都是属于类的,为类服务,构造函数是为了初始化对象,为对象服务。构造函数是用来生成实例,既然是实例就不是static的。这两者是相互矛盾的
public class Test1 {
public static void main(String[] args) {
Person person = new Person("小红",18);
System.out.println(person.name+" "+person.age);
}
}
class Person{
String name;
int age;
public Person(){
}
public Person(String sname,int sage){
name = sname;
age = sage;
}
public static void run(){
System.out.println("跑");
}
}
this
this.谁就是谁的意思
public class Demo1 {
public static void main(String[] args) {
Person person = new Person("小红",18);
System.out.println(person.name+" "+person.age);
}
}
class Person{
String name;
int age;
public Person(String name,int age){
this.name = name;
this.age = age;
}
public static void run(){
System.out.println("跑");
}
}
hashCode
对象. hashCode,显示“地址”
public class Demo1 {
public static void main(String[] args) {
Person person = new Person();
System.out.println(person.name+" "+person.age);
}
}
class Person{
String name;
int age;
public Person(){
this("hong",12);//访问构造器的这句话,必须要放在第一句话。
//不能用在普通方法种
}
// public void f1(){
// this("",22);
// }
public Person(String name,int age){
this.name = name;
this.age = age;
}
}
Random
生成随机数方法
import java.util.Random; public class Demo1 { public static void main(String[] args) { Person person = new Person(); person.m1(); System.out.println(person.random.nextInt()); } } class Person{ Random random = new Random(); int a = random.nextInt(3);//0-2随机数 public void m1(){ System.out.println(a); } }
包的使用(介绍一下就行)
访问修饰符
default就是默认修饰符,没有修饰符
静态方法和实例方法的区别
(1)静态方法通过“类名.方法名”,也可以通过对象名.方法名。
(所以调用静态方法无需创建对象)
静态方法不允许访问类的非静态成员(包括成员的变量和方法),因此是通过类调用的,没有对象的概念,this->data不能用!!!
(2) 但是实例方法只能通过对象名.方法名
同类
package Day;
//同类都可以
public class Demo1 {
public int a = 1;
protected int b = 2;
int c = 3;
private int d = 4;
public void m1() {
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
public static void main(String[] args) {
// System.out.println(a);
Demo1 demo1 = new Demo1();
demo1.m1();
}
}
同包
package Day;
//同一包下
public class Demo2 {
public static void main(String[] args) {
Demo1 hhh = new Demo1();
System.out.println(hhh.a);
System.out.println(hhh.b);
System.out.println(hhh.c);
// System.out.println(hhh.d);
}
}
子类
先暂时跳过哟,与继承有关
不同包
package Day2;
import Day.Demo1;
public class Demo3 {
public static void main(String[] args) {
Demo1 demo1 = new Demo1();
System.out.println(demo1.a);
// System.out.println(demo1.b);
}
}
方法和属性修饰符一样用