一、new对象实际上就是调用类的构造方法,这就是“类的构造方法”
Person:
package day06.test;
public class Person {
//默认构造方法前面的访问修饰符(例如下面的public)和定义的有关,类是public方法就是public,类是缺省方法就是缺省
public Person(){}//调用此方法来new一个Person
/**
* 如果不写构造方法,系统会自动给一个默认方法
*/
}
Test:
package day06.test;
public class Test {
/**
* 我们是如何实例化对象的呢?
* 怎么new出来呢?
* 实际上是调用了Pernson的方法Person(){}
*
*/
Person p= new Person();
}
Person2:
package day06.test;
public class Person2 {
/**
* 如果显示的定义了构造方法,那么就会使用显示的方法
*/
// public Person2(){
// age=1;
// name="zhangsan";
// }
/**
*带参数的构造方法
*/
public Person2(int a,String n){
age=a;
name=n;
}
public int age;
public String name;
public void shouInfo(){
System.out.println(age);
System.out.println(name);
}
}
Test2:
package day06.test;
public class Test2 {
public static void main(String[] args) {
//此种方法是在new对象的时候能够自己给属性不同的值
Person2 p2=new Person2(2,"lisi");
p2.shouInfo();
}
}
运行截图
练习5.1
Person3:
package day06.test;
public class Person3 {
public Person3(){
age=18;
}
public int age;
}
Test3:
package day06.test;
public class Test3 {
public static void main(String[] args) {
Person3 p3=new Person3();
System.out.println(p3.age);
}
}
运行截图
练习5.2
Person3:
package day06.test;
public class Person3 {
public Person3(int a,String n){
age=a;
name=n;
}
public int age;
public String name;
}
Test3:
package day06.test;
public class Test3 {
public static void main(String[] args) {
Person3 p3=new Person3(18,"wang");
System.out.println(p3.age);
System.out.println(p3.name);
}
}
运行截图
练习5.3
Point:
package day06.test;
public class Point {
public Point(int m,int n,int k){
x=m;
y=n;
z=k;
}
int x;
int y;
int z;
public void setPoint(int m,int n,int k){
x=m;
y=n;
z=k;
}
}
PointTset:
package day06.test;
public class PointTest {
public static void main(String[] args) {
Point p=new Point(1,2,3);
p.setPoint(1,2,3);
}
}
练习5.4
TriAngle:
package day06.test;
public class TriAngle {
private int base;
private int height;
public TriAngle(int a,int b){
base=a;
height=b;
}
public int jisuan(){
return base*height/2;
}
}
TestTriAngle:
package day06.test;
public class TestTriAngle {
public static void main(String[] args) {
TriAngle t=new TriAngle(2,3);
System.out.println(t.jisuan());
}
}
运行截图: