所有的类都是继承于 Object
类,该类有一个 toString()
方法,打印对象时调用
class Person4 extends Object{ // extends Object 可省略
String name = "Michael";
int age = 18;
}
class test4{
public static void main(String[] args)
{
Person4 p = new Person4();
System.out.println(p);
}
}
输出:
Person4@1b6d3586
toString()
class Person4 extends Object{ // extends Object 可省略
String name = "Michael";
int age = 18;
public String toString(){
return "I am " + name + ", age " + age;
}
}
class test4{
public static void main(String[] args)
{
Person4 p = new Person4();
System.out.println(p);
}
}
输出:
I am Michael, age 18
class Outer{
int score = 95;
void inst()
{
Inner in = new Inner();
in.display();
}
class Inner{
void display()
{
System.out.println("score: " + score);
}
}
}
class Outer{
int score = 95;
class Inner{
String innerName = "Michael";//外部类无法访问
void display()
{
System.out.println("score: " + score);
}
}
}
class test4{
public static void main(String[] args)
{
Outer out = new Outer();
Outer.Inner in = out.new Inner();
// 用外部类的对象 去实例化一个 内部类的对象
in.display();
}
}
class Person4 extends Object{ // extends Object 可省略
private String name = "Michael";
private int age = 18;
public Person4(String name, int age)
{
this.name = name;
this.age = age;
}
}
class test4{
public static void main(String[] args)
{
Person4 p1 = new Person4("Michael", 18);
Person4 p2 = new Person4("Michael", 18);
System.out.println(p1.equals(p2) ? "eq" : "not eq");
// not eq , 不覆写 equals , 不对劲,内容一样的.
}
}
class Person4 extends Object{ // extends Object 可省略
private String name = "Michael";
private int age = 18;
public Person4(String name, int age)
{
this.name = name;
this.age = age;
}
// 覆写父类 Object 的 equals
public boolean equals(Object o)
{
boolean eq = true;
Person4 p1 = this;
if(o instanceof Person4)
{
Person4 p2 = (Person4) o;
eq = (p1.name==p2.name && p1.age==p2.age);
}
else
eq = false;
return eq;
}
}
class test4{
public static void main(String[] args)
{
Person4 p1 = new Person4("Michael", 18);
Person4 p2 = new Person4("Michael", 18);
System.out.println(p1.equals(p2) ? "eq" : "not eq");
// eq
}
}
//接口对象实例化
interface Usb{
public void start();
public void stop();
}
class MoveDisk implements Usb
{
public void start(){
System.out.println("MoveDisk start...");
}
public void stop(){
System.out.println("MoveDisk stop...");
}
}
class Mp3 implements Usb
{
public void start(){
System.out.println("Mp3 start...");
}
public void stop(){
System.out.println("Mp3 stop...");
}
}
class Computer{
public void work(Usb u){
u.start();
u.stop();
}
}
new Computer().work(new MoveDisk());
new Computer().work(new Mp3());
输出:
MoveDisk start...
MoveDisk stop...
Mp3 start...
Mp3 stop...
只能在构造函数中使用,且放在第一句
static { ... }
只会被执行一次,经常用来类属性初始化对象 instanceof 类(或接口)
,返回 boolean