课时43|封装-方法重载,包的实现和利用

来源:互联网 发布:手机淘宝卖家中心在哪? 编辑:程序博客网 时间:2024/06/12 22:32

同一个包内的代码可以互相访问

构造方法的重载:
1.一个类里面可以有多个构造方法
2.构造方法没有返回值
3.通过调用不同的构造方法来表达对象不同的初始化方式。(所以构造方法只能用一个?No. 使用不同的参数列表,调用对应的构造方法,可以同时使用多个构造方法哦)

java中可以出现同名方法。
方法签名(方法名+参数列表)是判断方法是否相同的依据:
method(String name)
method(String name, int name)
同名不同参的方法叫做重载方法,方法重载必须参数不同
仅有返回类型不同的方法不能成为重载,方法的重载和方法的返回类型毫无关系。

public class overloadDemo{    public static void main(String []args){        printer p=new printer(2999.89);    //init a object with price 2999.89 and default brand          p.print("Hello");  //call method print with parameter string        p.print(10000);    //call method print with parameter int        printer p1=new printer("Sony",2779.89);  //init a object with price 2779.89 and brand Sony        p1.print("Hello");   //call method print with parameter string        p1.print(10000);     //call method print with parameter int    }}class printer{    private String brand="HP";    private double price;    public printer(double price)   //run as object only has price    {        this.price=price;    }    public printer(String brand,double price)    //run as object has brand and price    {        this.brand=brand;        this.price=price;    }    public void print(String content)   //print brand value    {        System.out.println("Brand "+this.brand);    }    public void print(int content)  //print price value    {        System.out.println("Price "+this.price);    }}

package打包规则:
1.第一行package声明
2.全部用小写字母
3.互联网域名的倒置
4.同一个包中的类可以互相访问
5.通过两种方式可以访问其他包中的公开类
1)在每个类前面加上完整的包名。
2)顶部(package下面)import导入(导入特定类或者整个包)

打包编译:javac -d . tittle.java
最终的class文件会在package包内

package com.iotek.entity;public class DogTest{    public static void main(String []args){        Dog dog=new Dog("Pony",3,"teddy");        System.out.println(dog.show());    }}
package com.iotek.entity;public class Dog{    String name;    public int age;    public String brand;    public Dog(String name,int age,String brand){        this.name=name;        this.age=age;        this.brand=brand;    }    public String show(){        return this.name+" is a "+this.age+" years old "+this.brand;    }}
0 0