开发者

Difference between class and package

What is the difference between a class and a package in开发者_开发问答 Java ?


A class is a declaration (and often implementation) which encapsulates the members properties and methods which instances of that type will posses. You can create instances of a class as distinct, individual objects that behave as specified.

A package is simply a namespace under which you can categorize classes, analogous to a "folder" or "path", so you can group classes with related purpose or functionality.

Don't be confused by the fact that Java has classes which represent both the concept of a Class and a Package which are useful for inspecting the structure of Java programs at runtime. They are merely models of the general concepts described above.


Quite simply a java package is a namespace where classes are organized based on the same category or functionality

Java classes is an object that consists of behaviours (methods), properties (variables), constructors (if any, for object creation), etc. that exists inside a folder (package).


A class is like a Template, where an you put set Behaviors (Methods) and properties (Instance variables) which every Object of its kind will Posses.

but package is totally different and has nothing to do with technical part. It is just for the purpose of Readability and Organizing your code. you have to put classes with different behaviour in diff package. thats it.


Package is a mechanism for organizing Java classes into namespaces. Java packages can be stored in compressed files called JAR files, allowing classes to download faster as a group rather than one at a time.

on the other hand, a class is a programming language construct that is used to group related instance variables and methods. Each class expresses structural and behavioral design decisions made by the programmer to indicate what types of objects can exist when the program is executed.

Reference: Coders2020


For understanding it more clearly,just think a package as a box of toolset. You have various tools in a toolset box i.e a screw driver,cutter,cutting pliers etc. Each tool set box is a package which is collection of various tools ( classes). Now here each tool ie a screw driver is a class , cutter another class etc, each of tool having their own properties and purpose ( operation).In the similar way you have many toolsets designed for domestic,industrial purposes which can be compared to different packages.

Hope this helps :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜