0% found this document useful (0 votes)
78 views

Classes and Objects, Packages

This is a pdf regarding to classes, objects and packages

Uploaded by

19K41A0 450
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
78 views

Classes and Objects, Packages

This is a pdf regarding to classes, objects and packages

Uploaded by

19K41A0 450
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 77
_— In this module you will learn - mp TEKNOTURF * Classes and Objects * Access Specifiers * Usage of Getters and Setters Classes and Objects What is an Object * Any real world entity with well defined properties is called an object. * Object will have a state, behaviour and a unique identity * Objects can be tangible (physical entity) or intangible (cannot be touched or felt) Awooden chair Achemical process A transaction Classes and Objects ap Wel ics * Aclass is a template or blue print that describes the behaviors/states that an object of its type supports * Aclass defines its - object’s properties and - object’s behavior through methods TEKNOTURF Classes and Objects ere eed ag secre) rT Tee eg Lee Lael a Re es tee eee ceric * Class is a description of the object * It describes the data that each object possesses * It also describes the various behaviors of the object Oy ead eS Ute Rr Classes and Objects Employee 1D :101 Name : Rohith Salary : 25000.00 ia Class: Employee Employee: Object = = TEKNOTURF class Employee { //Attributes int emplD; String name; double salary; {Methods void punchCard() { /1d0 something } void doProject() { Ido something } } Classes and Objects TEKNOTURF model = “Mustang” Color = “Yellow” numofPassengers = 0 amtOfGas = 16.5, Behaviour: ‘Add / Remove Passenger Get Tank Filled Report when out of Gas class Car { //mtributes String model; String color; int numOfPassengers; floatamtOfGas; {Methods void addPassenger() { // do something } void removePassenger() ; 1 do something velftnip ; // do something voldreprt wots) : 1 do something ; } Class Declaration Declaring a class eC eomiCont Sea eR ena” Reeietetat ei Example: Cite eesur Peas urTc} Meco Ca aL TESA Cu ect ET cer ct TEKNOTURF Attribute Declaration Attributes/Fields are used to declare the properties of a class, These Settee eee Ree eC ol oo They can be intrinsic types (int, boolean...) or user-defined type Cee eur Tt * * * [ = ] Example: private double salary; Method Declaration a Methods describe the responsibility of the class. These ‘TEMNOTURF * * ( * ) { * } Example : public boolean isAgeValid() { ublic void calculateAreaint side) { an 2 iffage>0 && age <=100) intarea = side * side; return true; system.out.printin(area); ; else return false; } Create Object =! eeernaels tas TeRNOTURE '* Objects are created for a class using the keyword new. * In Java, all Objects are created at run time in the heap area. pe ime reference. variable= new class_name() eens + Employee e=new Employee(); Here variable ‘e’ is the. name of the object. ‘e’ is Create Object and Access Members = The attributes and methods of a class can be accessed using the dot operator as . TEKNOTURF /object creation Employee empObj=new Employee(); /assign meaningful state empObj.empid(101); empObj.name(“Rohit”); empObj.salary(25000); /retrieve values System.out.printin(“Emp ID "+empObj.empld); System.out.printin(“Name "+empObj.name); ‘System.out.printin(“Salary "+empObj.salary); Class Example public class Employee { JINtributes int empid; String nam double salary; Himethods public double calculateGrossPay{int bonus) t return salary + bonus; TEKNOTURF public cass EmployeeMal ( public statle vold main(String af) i object creation {Employee empobj-new Employeet); assign meaningful state cempObj.empld=101; ‘empObj.name= "Rohit cempObj-alary=25000; Ihetvieve values System.out.printin(*Emp 1D "+empObj empl); system.out printin(’Name “sempObj1name); system.out.printin('alary "sempObj salary); system.out.printin("Gross Pay "+ calculateGrossPay(8000)); Accessors and Mutators = TEKNOTURE Encapsulation is an important OO Concept. How is encapsulation implemented in Java? By wrapping up of data and methods, that operate on that data into a single unit, class Data inside a class needs to be secure. Declare the data in a class as private, No outside class can access private data members of other class. Outside classes should be able to read and update the private data members only by using the public methods. ‘These methods are called Accessors or Getters and Mutators or Setters. Data Hiding is not possible without Encapsulation. Accessors and Mutators | . = _ to return _ value : a private _ ‘* Does not change the state of the Object + Example + Vics ‘* Method used to set a value of a private field * Changes the state of the Object _ = Create Object and Access Members Weegee ue kc) //object creation Employee empObj=new Employee(); //assign meaningful state using Setters empObj.setEmpld(101); empObj.setName(“Rohit”); empObj.setSalary(25000); //retrieve values using Getters System.out.printin(“Emp ID "+empObj.getEmpld()); System.out.printin(“Name "+empObj.getName()); System.out.printin(“Salary "+empObj.getSalary()); class Example public class Employee ( (attributes private int empid; private String name; private double salary; //Accessors or Getters public int getémpld() { return empld; ) public String getName() ( return name; ) TEKNOTURF public double getSalary() { return salary; 1 //Mutators or Setters public void setEmpld{int id) { empid = id; 1 public void setName(String namet) { name = namel; 1 public void setSalary(double sal) { salary = sal Create Object and Access Members a public class EmployeeMain public static void main(String al)) i [[cseate Object Employee empobj-new Employee(); Hassign meaningful state empObjsetémpld(101); empObj.setName(“Rohit”); empObj.setSalary(25000); retrieve values and print System.out.printin(“Emp ID "4empObj.gettmpid()); System.out printin("Name “tempObj getName()}; System.outprintin( "Salary "sempObj getSalary(); TEKNOTURF Employee Main class depicts how to create an object for the Employee class. It also shows how to access the members of the class using that object. Access Specifier public «= private * protected ‘= default(no specifier) Access Specifier a TEKNOTURF * Classes, methods, and fields declared as public can be accessed from any class in an application * Ifclasses, variables, and methods have a default specifier we can access them only within the same package, but not from outside this package ‘When no access specifier is specified for an element, its * Private methods and fields can only be accessed within the same class to which the methods and fields belong accessibility level is default. *There isno keyword default. default Access Specifier meer Accessible inside the class Accessible within the subclass inside the same package Accessible outside the package Accessible within the subclass outside the package ‘TEKNOTURF default private protected publ yes yes yes yes yes no yes yes Pes eee cri protected, subclass and Seco In this module you will learn - BD TEKNOTURF Constructor — Default and Parameterized ‘this’ reference Constructor Overloading Method Overloading Constructor - Overview TEKNOTURF How can we create an object of the employee shown here using Java? Employee ID : 101 Employee e=new Employee() Name : Rohith Salary : 25000.00 But the id is 0, name is null and salary is 0.0. It is not valid. How to create the object with proper state? Let us discuss this concept now. Constructor = Consider the following statements Employee e1=new Employee(); Employee e2=new Employee(); Employee e3=new Employee(); empld=0 ——(— name=null TEKNOTURF Note : Objects are created. They are notin proper state. Instance variables are allotted the default value. Constructor y TEKNOTURF eon eee Rue cena Oeiad eter It initializes the instance variables with proper value PMCS eRe acs * Constructor name must be the same as the name of the class * Constructors must not have a return type (not even void) Aree * Default Constructor * Parameterized Constructor Default Constructor a Default Constructor (no argument constructor) reaorane A constructor with no arguments is known as a default constructor Example public class Employee { private int empid; private String name; private float salary; public Employee) { ‘System. out.printn(“Default Constructor, scl td ) public static void main(String af) ‘ Employee e-new Employeet); 1 a empld=0 i name=null salary=0.0 Output : Default Constructor Parameterized Constructor a public class Employee. { ppublic static void main(String af) private int empid; ( private String name; Employee e=new Emplayee(101,"Rohith"); private float salary; Hconstructor public Employee(int id,String ename) [ Output : In Parametrized Constructor System.out printin(“In Parametrized constructor”); ‘empld = id; name = ename; Constructors TEKNOTURF * Ifa constructor is not written explicitly for a class, what happens when an object is created? — Java compiler builds a default constructor for that class and initiates the fields with the default value. * When a constructor is explicitly written by the developer, the compiler will not provide the default constructor. * Ifa constructor with parameters is declared and we want to create an object using no argument constructor, we must explicitly write a no argument constructor. “this" keyword Output of this code = ID: 0. Name = null The reason for this outputs: parameter and instance variableshave the same name The solution for this problemis to use the keyword “this” _ Ugpiet a this" keyword iu US eC ee eR Rael) (aa Example : Usage of “this” in constructor for initializing the attributes class Employee( int empl; publicstatic void main(stringargst) String name; ( Employee e1= new Employee(101,"Tom"}; public Employee(int empld Stringname) eldisplay) ( ) ‘this.empld = empld } this name= nam ) is becerer Output of this code : { ‘system out printin("ID :“sempld+" Name: "+name); 'D: 101 Name: Tom } Com] “this” keyword = TEKNOTURF Seen em emia diffinArea(Rectangler) length=12.0 breadth=15.0 Invoke r1.diffinArea Constructor Overloading TEKNOTURF eee ee a Peas Meer te eRe rare giec tl cae aay Menu iy * Number of parameters * Type of parameter + Order of parameter The compiler identifies which constructor is to be invoked based on the number Cee ec ur Rigs ts Constructor Overloading public class Rectangle { private float length; private float breadth; {Constructor Overloading public Reetangle() fl length-0; breadth-0; ) public Rectangle(fioat length, float breadth) ‘ thisength = length; this.breadth = breadth; } public static void main(String af]) { ) [Rectangle r1-new Rectangle(); | Rectangle r2-new Rectangle(12,15); length=0.0 breadth=0.0 TEKNOTURF Invoking a Constructor ap public class Employee ( ‘public Employee(int empid, String ame, private int empid; double salary, String private String name; Teplta private double salary; : this(empid.name salary); private String panno; this.panto = panNo; , llc Employee(int empl, String name, double sala . Employee(int empid, — y Note: this() should be the: this.empld = empld; first statement in the this.name = name; this.salary = salary; coe Method Overloading TEKNOTURF * Ina class, if there is more than one method with the same name, but differing in parameters, those methods are called overloaded methods. This concept is called Method Overloading sing_a_Song() sing_a_Song(illness) { { smooth and clear lots of disturbance } } Method Overloading = TEKNOTURF Rules for Method Overloai ‘* Methods should have samename but different arguments list ‘+ Argument list should differ in + Number of parameters ‘© Type of parameter * Order of parameter ‘+ Return Type of the method is not to be considered Method Overloading Number of Arguments are the same, but vary in the type public int add(int num4,int num2) { return num1+num2; } public int add(int num4,int num2,int num3) i return num1+num2+num3; } public String add{String s1,String s2) { return s1+s2; k Vary in Number of Arguments TEKNOTURF Method Overloading Ne aC Cay 1. public void calculateArea(int a,int b) {} Public void calculateArea(float a fioat b) {} public void calculateArea(inta){ } public void calculateArea(inta float b) {} eee ae 1. public void calculateArea(int a) {} public int calculateArea(int a) { } Not valid because the number of argumentsis same and the changeis only in the return type. 2. public void calculateAreatint a int b) {) public void calculate@rea(floata, float b) 2. public void calculateArea(int a) { } public void calculateArea(intx) {} th 3. public void calculateAreatint a, float b) { } public void calculateArea(fioata,int b) {} Not valid because the signatureis same TEKNOTURF —_— In this module you will learn - mp TEKNOTURF * Usage of static keyword * static variable and methods * static block * Initialization block Static Certain things are available for each individual apartment, whereas certain things are common for all apartments. static TEKNOTURF When an object is created for a class, it will have its own copy of variables, called instance variables. Certain fields are common to all objects in a class. We call these variables as class variables. These variables are also called static variables because they are declared with the keyword static. Static keyword is used as a modifier on variables, methods, block and nested classes. A static modifier associates an attribute or method to the class as a whole, rather than as any particular instance of that class. To access an instance member, an object is required. Whereas, static members can be accessed directly using the class name itself as className.staticmember “this” cannot be referenced from a static context. static variable TEKNOTURE class Employee publiestatievoid main(String al]) { { private int empid; Employee e1=new Employee(101,"Rohith’); private String name; Employee e2-new Employee(102;"Tom") private static String System.out.printin(“ComparyNameis"*+ companyName="Teknoturf” Employee.companyName); Uhl also work 1/System.out.printin("Company Nameis “+ JiConstructor eLcompanyName); public Employee(int empid.string name) (| this.empld=empid; ) this:name-name; stack Heap ‘empid=10 Class Area name=Rohith _ ="Teknoturf” empld=102 name=Tom static variable class Employee ( private int empld; private Stringname; privatestatle int count; Constructor publicEmployee(intempld.stringname) { this.empld=empld; ‘TEKNOTURF publicstaticvoid main(Stringal)) ( sw Employee({01,"Rohith’}; sw Employee(102,"Tom") ‘ystem.out.printin(“Total Objects Created: “+ Employee.count); //2 {This will also work (/fSystem.out.printin( “Total Objects created : “+ elcount+”“‘e2.count); //2 2 ’ ) Heap ‘empid=101 name=Rohith —) Class Area empld=102 name=Tom static method public class Employee { private int empld; private String name; private static int count; Hconstructor public Employeetint empld.String name) { this empid-empid; this.nam counts; , public void setEmpid{int empld) i this empld = empid; TEKNOTURF public void setName(String name) ( this.name = name; public int gettmpia) static method can t access only static members. return empld; } public String getame() i return name; , public static int displayCount() { return count; _ i = static method | reworune public class EmployeeMain: { public static void main(String af]) { Employee e1=new Employee(101,"Rohith"); Employee e2=new Employee(102,"Tom"}; System.out.printin("Count of objects : "+Employee.displayCount()); //Count of objects 22 Static method accessed. directly using class name static =» TEKNOTURF A static method can access only other static members of a class. Anon-static method can access all members i.e., both static and non staticmembers of a class. The main() method in java is public static, public access specifier denotes anyone can access/invoke it, such as JVM. static keyword allows main() to be called before an object of the class has been created, main() is called by the JVM before any objects are made. As itis static, itis directly invoked from class. static = TEKNOTURF UTM are R Reale ek Cee public static void main(String a[]) public static void main (String[] args) command line To call by VM argument from anywhere without existing object also JVM has to call this method name of method configured in JVM main method can’t return anythingto JVM static block aD TEKNOTURF + Static variables can be initialized using the static block + Static block gets executed when the class gets loaded in the memory + There can exist multiple static blocks. They get executed in the same order in which they are written in the code Initialization block =» TEKNOTURE * Instance Initialization Blocks are used to initialize instance variables * Initialization blocks are executed whenever an instance is created for that class and before constructors are invoked. Output In Initial In constructor In this module you will learn - mp TEKNOTURF Wrapper class and its usage Convert primitive to wrapper and vice versa Convert String to primitive Autoboxing and unboxing concept Scanner class and its usage Wrapper Class ap TEKNOTURF Object representation of primitive data types are called wrapper classes. Wrapper Class Wrapper class wraps around a data type and gives it an object appearance Use this object wherever primitive is required as object Wrapper class has methods to unwrap the object and give the data Wrapping unwrapping Wrapper Class byte Byte short Short int Integer long Long float Float double Double char Character boolean Boolean TEKNOTURF Instantiating Wrapper Class a TEKNOTURF Il Wrapper classes can be instantiated using their primitive type as the argument * Integer iobj=new Integer(10); * Double num=1 * Character cobj * Boolean isdone=new Boolean false); int b=it1.intValue(); ——sUnwrapping Type casting = TEKNOTURF Integer num = new Integer(4); float fit = num.floatValue(); //stores 4.0 in fit Double dbl = new Double(8.2) int val = dbl.intValue(); //stores 8 in val int num4 = Integer.parseint(“3”); double num2 = Double.parseDouble(“4.7”); Wrapper Class — Autoboxing & Unboxing =» TEKNOTURF * Converting a primitive value into an object of the corresponding wrapper class Example : Integer i=10; * Converting an object of a wrapper type to its corresponding primitive value Example : Integer i=10; // boxing inty =i; // unboxing Wrapper Class — autoboxing & unboxing Integer y = new Integer(567); _// wrapa data type intx= y.intValue(); [unwrap it xt; Ifuse it y= new Integer(x); I] re-wrap it Integer y=new Integer(567}; _// make it yes // uowrapit, incrementit, eewrap it system.out.printin(*'y="+y}; _// printit — Scanner Class gD TEKNOTURF System.out is used to display the output text on the console on executing a java program System.in is used to get the input from the user, but not directly | Scanner import java.util package to get input using Scanner Scanner class parse the input into tokens based on the delimiter Default delimiter is whitespace The delimiter is recognized by Character.isWhitespace(char) Delimiters other than whitespace can also be used The resulting tokens are then converted into values of different types using various next methods Scanner mp Texnovne To get input from the keyboard + Create a Scanner object ‘Scanner sc=new Scanner(System.in); + Methods to read tokens from a Scanner class nextByte() nextint() nextShort() nextLong() nextFloat() nextDouble() nextBoolean() next() nextLine() Scanner byte b = sc.nextByte(); int num = sc.nextint(); String city = sc.next(); String sentence = sc.nextLine(); // reads till the end of line <= Scanner gD TEKNOTURF + Sample Program import java.utilScanner; publicclassScannerDemo { publicstaticvoid main(String afl) { ‘Scanner sc=new Scanner{System.in); byte b = sc.nextByte(); shorts = sc.nextShort(); intx = se.nextint(); long = sc.nextLong|); float f = sc.nextFloat(); doubled = sc.nextDouble(); boolean status=sc.nextBoolean(); String city = sc.next(); ‘String name = sc.nextLine(); char gender = sc.next().charAt(0); //String method charAt(0) is used In this module you will learn - To TEKNOTURF Package and its usage Creation of Package Usage of import statement Access restriction using packages Building class path Usage of static import Modularity * Modularity is a way to break a program into smaller units * Modularity is implemented in java as packages : : : . Modularized How to take the music files alone? Now its easy for me to get the file Packages Package Employee class employe dase Used to group semantically related classes Help to manage large software systems Can contain classes, interfaces and sub-packages Are created using the keyword package Help in removing name collisions and providing access restrictions — Package Creation up TEKNOTURF Packages are created using the keyword “package” Package should be the first statement in the source file All packages in java start with java or javax Design Guide lines TEKNOTURF Only related Pen classes should should be in be kept in the lowercase same package Package names are usually Tar named with He reverse internet URC domainname |< of the company mymathis the package created by the programmer at com.info Example package class { Mogic Calculatorjava package mymath; public class Calculator{ private int num1=10; private int num2=20; public int addTwoNum(){ return numi+num2; ‘TEKNOTURF Compile and Execute * javac -d sourcefile * -d is used to inform the compiler to create a package structure * specifies the location where the package needs to be created. © (dot) specifies the current directory * javac -d . Calculator.java To execute * java © Fully qualified class name is package name.class name * java mymath.Calculator > Sub packages | Packages are usually defined using the hierarchical naming pattern To create a sub package each level is separated using periods (.) Example com.info.mymath import —— IKNOTURF +import j.].; oR + import -{esub_pkg_name>.]*; + Precedes all class declarations + Tells the Compiler where to find the classes + import _ imports the class of that package in the current package + import *1s a wild card character that imports all the classes in the current package + Fully qualified classname Use fale cocina Cah Scene ERENT Weert tes en the chess eames ts the ee Se Example for import package com.infotech.mymath; publicclass Caleulator( privateintnumt; privateintnum2; publieCaleulator() publicint addTwoNum(){ return numL+num2; ’ , package com.infotech.mydriver; import com.infotech.mymath.Calculator; // 1" way public class CalculatorTest{ public static void main(String{] args) {Calculator cobj=new Calculator(); ‘System.out.printin(cobj.addTwoNum()}; 7 TEKNOTURF — Example Contd up TEKNOTURE package com.infotech.mydriver; import com.infotech.mymath.*; //2™ way public class CalculatorTest{ public static void main(String{] args) { Calculator cobj=new Calculator(); ‘System.out.printin(cobj.addTwoNum()); 2 } package com.infotech.mydriver; public class CalculatorTest{ public static void main(Stringl] args) { com.infotech.mymath.Calculator cobj=new com.infotech.mymath.Calculator();//3" way ‘System.out.printin(cobj.addTwoNum()); } J ectory Layout and Packages BD TEKNOTURF Te Ce eae Reece mec infotech\ mymath\, Se MR coon Rec Ae ac) Caleulator.class mygeiver\ TT CaleulatorTest.class CLASSPATH Compiler searches these directories to look for the needed .class files CLASSPATH is set one level above the package. CLASSPATH can be set in two ways * Asan environmental variable ‘+ Using the command line — classpath option Example : To set in windows set classpath=%classpath%; Static import BD TEKNOTURF Import all the static fields and methods of the Math class import static java.lang.Math.*; double val= PI; + Import a specific field or method import static java.lang.Math.abs; double d= abs(-10.4); Core Java Packages * Provides classes that are fundamental to the design of the java programming language * Imported implicitly for any java program * Example: Wrapper classes, String, StringBuffer, Object TEKNOTURF java.util * Contains Collection Framework, Date and time , Internationalization Support and utility classes java.io * Contains classes for Input/Output Operations TEKNOTURF Core Java Packages SENECA UCL) * Provides classes for performing arbitrary precision integer arithmetic(Big Integer) and arbitrary precision decimal arithmetic(Big Decimal) java.sql * Provides the API for accessing and processing data stored in the data source(usually a relational database) IER * Provides classes and interfaces for handling text, dates, number and messages in a manner independent of the natural languages

You might also like