4 Packages

download 4  Packages

of 37

Transcript of 4 Packages

  • 8/14/2019 4 Packages

    1/37

    1Java

    Packages

  • 8/14/2019 4 Packages

    2/37

    2Java

    Java source file rules12

    Static Imports11

    Packages in JDK10

    Imports9

    jar command8

    Jar7

    Result of execution6

    Compiling and executing5Default Access Specifier4

    Solution !3

    Executing classes in a package2

    Definition1

    CONTENTS

  • 8/14/2019 4 Packages

    3/37

    3Java

    What packages are in Java

    How default access specifier works.

    Java source file coding rules.

    Some of the packages in java.

    Know

  • 8/14/2019 4 Packages

    4/37

    4Java

    Be Able To

    Use import and work with packages

    Implement static import

  • 8/14/2019 4 Packages

    5/37

    5Java

    I want you to create a class

    which will calculate gradesfor students based on

    percentage of marks. A

    student who gets above 90

    has a grade O, a student

    who gets between 80 and

    90 gets a grade A, student

    who gets between 70 and

    80 gets B and between 60

    and 70, C. Below 60 is

    fail.

    Project Manager

  • 8/14/2019 4 Packages

    6/37

    6Java

    Thats simple. I can do itwith my eyes closed .

    public class Grade{/* get registrationnumber and % marksand assign thegrade */

    }

    You

  • 8/14/2019 4 Packages

    7/37

  • 8/14/2019 4 Packages

    8/37

    8Java

    for reasons of performanceappraisal, we want teachers

    grading also. Students of a class

    will grade the faculty based on

    his or her performance in the

    class. The head of the

    department will look at thegrades to do the performance

    appraisal. We need to automate

    this.

    No problem!

  • 8/14/2019 4 Packages

    9/37

    9Java

    What should I name the teachers grade class. Icannot have Grade class again !

    TeacherGrade class.

    Yes ! But It doesnt look ok. For students

    Grade class and for teachers TeacherGradeclass. Oh ! Should I then change the studentsgrade class to StudentGrade class. I will haveto do so much of rework. But I have alreadytold the PM that I am almost finished. He mayask for it tomorrow. I am stuck!

    If only I had used packages!

  • 8/14/2019 4 Packages

    10/37

    10Java

    Definition

    A grouping mechanism that holds classes andpackages

    Classes can be grouped under a package for reasonsof similar / shared responsibilities, for reasons of

    organization and so on Packages are implemented using file system

    directories.

    Syntax for creating Packages:

    package package_name[.package_name];public class Class_name{}

  • 8/14/2019 4 Packages

    11/37

    11Java

    student teacher

    Student

    Grade

    Teacher

    Grade

    student.StudentReferred to as

    Student

    Referred to as

    Teacher

    Referred to asteacher. Teacher

    package student;

    public classStudent{}

    Changing the

    student class

  • 8/14/2019 4 Packages

    12/37

    12Java

    package student;

    public class Grade {

    private Student student;private int mark[];private final static String O="Outstanding";private final static String A="V.Good";

    private final static String B="Good";private final static String C="Average";private final static String F="Fail";

    public static void main(String str[]) {Grade g=new Grade(new Student("Raja"),newint[]{ 80,85, 91,86, 82});System.out.println(g.getGrade()); }

  • 8/14/2019 4 Packages

    13/37

    13Java

    public Grade(Student s, int mark[]){this.student=s;this.mark=mark; }public String getGrade() {int percent=getPercent();if(percent>=90) return O;

    else if(percent=80)return A;else if(percent=60)return B;

    else if(percent=50)return C;elsereturn F;}

  • 8/14/2019 4 Packages

    14/37

    14Java

    int getPercent(){int tot=0;for(int i=0;i

  • 8/14/2019 4 Packages

    15/37

    15Java

    Let us first compile all the classes.Let us assumethat all the files are in D:\MyJava.

    D:\MyJava> java Grade

    Exception in thread "main"java.lang.NoClassDefFoundError: Grade (wrongname: student/Grade)

    Run time error is generated.

    Executing classes in a package

  • 8/14/2019 4 Packages

    16/37

    16Java

    Solution !

    A student folder has to be created and all the.class files generated for the student packagehas to be shifted there. This could be donemanually or by using the shortcuts during the

    compilation as given below. Shortcut during compilation:

    javac -d *.java

    D:\MyJava> javac d . *.java

    D:\MyJava> java student.Grade

    Executes the code successfully

    Creates a folder in the

    current directory and

    puts Student.class and

    Grade.class inside it.

  • 8/14/2019 4 Packages

    17/37

    17Java

    Default Access Specifier

    If no access specifier is specified then by default it is

    assumed to bepackage access specifierordefault

    access specifier.

    Classes or members having package access specifiercan be accessed only by the classes belonging to the

    same package.

  • 8/14/2019 4 Packages

    18/37

    18Java

    package student;package teacher;

    public class Student{

    private int regNo;

    public int getRegNo(){..}}

    public class StudentTest{

    void test1()

    public void test2()

    private void test3()

    }

    public class Teacher{

    ..

    }

  • 8/14/2019 4 Packages

    19/37

    19Java

    Teacher.java

    package teacher;public class Teacher{

    private int factId;private String name;private static int id;

    public int getFactId(){return factId;}public String getName(){return name;}

    public void setName(String name){this.name=name;private int generateId(){id++;return id; }

    public static int getId(){return id;} public

    Teacher(String name){this.name=name;factId=generateId();

    }}

    G j

  • 8/14/2019 4 Packages

    20/37

    20Java

    Grade.javapackage teacher;public class Grade{

    private Teacher faculty;

    private student.Student student;private String subjectCode;private String grade;

    public final static String A="EXCELLIENT";

    public final static String B="GOOD";public final static String C="AVERAGE";public final static String D="POOR";public Grade(Teacher faculty,

    student.Student student, String subjectCode,String grade){setFaculty(faculty);setStudent(student);setSubjectCode(subjectCode); setGrade(grade)

    ; }

  • 8/14/2019 4 Packages

    21/37

    21Java

    public Teacher getFaculty(){return faculty; }public void setFaculty(Faculty fact){

    this.faculty=fact; }

    public void setStudent(student.Studentstudent){this.student=student;}

    public student.Student getStudent(){return student;}

    public void setSubjectCode(StringsubjectCode){this.subjectCode=subjectCode; }public String getSubjectCode(){

    return subjectCode;}

  • 8/14/2019 4 Packages

    22/37

  • 8/14/2019 4 Packages

    23/37

    23Java

    public class Tester{public static void main(String str[]){

    /*accessing student package */student.Student s1= newstudent.Student("Malini");System.out.println("Name of the student "

    s1.getName()+"("+ s1.getRegNo()+")");student.Grade g=new student.Grade(news1,new int[]{ 80,85, 91,86, 82});System.out.println(g.getGrade());

    /*accessing teacher package */teacher.Teacher f=new

    teacher.Teacher("Tom");

  • 8/14/2019 4 Packages

    24/37

    24Java

    teacher.Grade gf= newteacher.Grade(f,s1,"001",teacher.Grade.B);

    System.out.println("Teacher Name "+gf.getFaculty().getName()+"-"+gf.getFaculy().getId());

    System.out.println("Student who graded "gf.getStudent().getName());

    System.out.println("Grade "+gf.getGrade());}

    }

  • 8/14/2019 4 Packages

    25/37

    25Java

    Compiling and executing Let us assume directory structure as given below:

    D:\MyJava : Student.java and Grade.java

    D:\MyJava1 : Teacher.java and Grade.java

    D:\MyJava : Tester.java

    Compile Student.java and Teacher.java first using doption.

    Set the class path to

    set classpath= %classpath%; D:\MyJava; D:\MyJava1

    Then compile Grade classes with d option

    Finally compile and execute Tester class.

  • 8/14/2019 4 Packages

    26/37

  • 8/14/2019 4 Packages

    27/37

    27Java

    Jar

    JAR(java archive) is a file which is a bundle of allthe class files required for an application.

    It helps us distribute our application files easily andalso helps in setting the classpath.

    Important thing about the jar file is that it maintainsthe directory structure. So if we want a classStudent.class to be inside student directory that can

    be maintained in the jar file.

    jar command can be used to create and update a jarfile.

    It also be used to extract a jar file.

  • 8/14/2019 4 Packages

    28/37

    28Java

    jar command

    Creation: jar cvf myjar.jar *.* Updation: jar uvf myjar.jar file.ext Extraction : jar xvf myjar.jar Example:

    Copy student and teacher package folders intoD:\packages.

    D:\packages >jar cvf college.jar *.class

    This jar file can now be copied and placed anywhere. To compile and execute Tester class set the classpath

    to the jar files location.

    Set classpath =%classpath%;path\college.jar

  • 8/14/2019 4 Packages

    29/37

  • 8/14/2019 4 Packages

    30/37

    30Java

    b) Importing all the classes in a package.

    Example:import student.*;

    public class Tester{

    Student s= newStudent("John","M.C.A.");

    }

  • 8/14/2019 4 Packages

    31/37

    31Java

    import student.*;import teacher.*;public class Tester1{

    public static void main(String str[]){

    /*accessing student package */Student s1= new Student("Malini");System.out.println("Name of the student "+s1.getName()+"("+ s1.getRegNo()+")");Grade g=new Grade(s1,new int[]{ 80,85,

    91,86, 82});

    System.out.println(g.getGrade());

  • 8/14/2019 4 Packages

    32/37

    32Java

    /*accessing teacher package */

    Teacher f=new Teacher("Tom");Grade gf= new Grade(f,s1,"001",Grade.B);System.out.println("Teacher Name "+gf.getFaculty().getName()+"-"+gf.getFacu

    lty().getId());System.out.println("Student who graded"+ gf.getStudent().getName());

    System.out.println("Grade "+gf.getGrade());}}

  • 8/14/2019 4 Packages

    33/37

    33Java

    The program does not compile?

    Can you figure out why ?

    How will you solve it ?

  • 8/14/2019 4 Packages

    34/37

    34Java

    Some of the important packages :

    java.lang : All the classes that are fundamental tothe Java programming language. String class is a

    part of java.lang package.

    java.util : All the utility classes like Date,LinkedList etc. which is frequently used by mostapplications.

    java.io : All the classes related to IO.

    java.sql : All the classes related to database.

    java.awt : All the classes related to building GUI.

    java.applet : Applet related classes.

    Packages in JDK

  • 8/14/2019 4 Packages

    35/37

    35Java

    Static Imports New feature in java 1.5

    Makes the static members of a class available to our codedirectly without us explicitly specifying the class name.

    Syntax:

    import static packageName.ClassName.*;

    (imports all the static members)

    Or

    import static

    packageName.ClassName.staticMember;(imports only the particularstaticMember available )

  • 8/14/2019 4 Packages

    36/37

    36Java

    Example

    import static java.lang.System.out;import static teacher.Grade.*;import teacher.*;

    class GradeTest{public static void main(String str[]){Teacher f=new teacher.Teacher("Tom");Grade gf= new Grade(f,new

    student.Student("Malini"),"001",B);out.println("Grade "+ gf.getGrade());}} Instead of Grade.B

    Instead of System.out.println

    Static member of System

    J fil l

  • 8/14/2019 4 Packages

    37/37

    37J

    Java source file rules A java source file can contain:

    b) a single package statement which will be the firststatement.

    c) any no. of import statements. They should bebetween package and class statement.

    d) any no. of classes with default access specifier. Insuch cases, the file name could be anything.java.

    e) only one public class. If there is a public class thenthe file must be named after the public class name.

    f) The package and the import statements apply to allthe classes in the source file.