封装
package com.ClassandObject;
public class Person {
//封:给属性和方法设定权限,其他类中便不能直接使用
//定义属性
public String name;
public int age;
public int id;
protected String gender;
//静态属性
static int number;
//使用静态属性来间接访问被private修饰的成员
static Person person2 = new Person("美玲",18,1,"女");//Expected 4 arguments but found 0
//构造方法
public Person(String name, int age, int id, String gender) {
this.name = name;
this.age = age;
this.id = id;
this.gender = gender;
}
//给属性赋值
//定义方法
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
if (age < 0) {
System.err.println("输入年龄有误");
}
this.age=age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
class Main{
//静态方法
static void staticMethod(){
System.out.println("静态方法");
}
public static void main(String[] args) {
Person person = new Person("美玲",18,1,"女");
System.out.println();
//person.setName("美玲");
// person.setAge(18);
System.out.println(person.getName());
System.out.println(person.getAge());
Person.number = 100;
System.out.println(Person.number);
person.number = 200;
System.out.println(person.number);
Person person1 = new Person("美玲",18,1,"女");
person1.number = 500;
Person.number=100;
person.number=300;
System.out.println(person1.number);
System.out.println(Person.number);
System.out.println(person.number);
//静态属性与静态方法都是可以由类直接调用,当然,对象也可以直接调用
Main.staticMethod();
//person.staticMethod();Cannot resolve method 'staticMethod' in 'Person'
//静态方法只能由类调用
//person.id = 1;'id' has private access in 'com.ClassandObject.Person'
//private 修饰的成员只能在本类中被访问 即不能在其他类中被访问
Person person3 = Person.person2;
person3.id=1;
System.out.println(person3.id);
}
}
单例模式
package com.ClassandObject;
public class King {
String name;
private King(String name) {
this.name = name;
}
static King king1 = new King("乾隆");
public void Method1 (){
System.out.println(name+"国王执行方法1");
}
public void Method2 (){
System.out.println("国王执行方法2");
}
public void Method3 (){
System.out.println(name+"国王执行方法3");
}
}
class main{
public static void main(String[] args) {
//King king = new King("乾隆");
King king = King.king1;//Non-static field 'king1' cannot be referenced from a static context
king.Method1();
king.Method2();
king.Method3();
}
}