Unit Ii Classesnobjects

  • Uploaded by: reddy
  • 0
  • 0
  • July 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Unit Ii Classesnobjects as PDF for free.

More details

  • Words: 2,157
  • Pages: 9
Classes & Objects Concepts of classes and objects: Java is an object oriented programming language. An Object-oriented system is a collection of objects which have their attributes and behavior. An object is anything that is of some interest to an application under development. An object may represent some real life entity, or an event, or some aspect of solution strategy to a given business problem. For ex in sales , the product can be represented as an object. In library management system the faculty, students, books etc are all objects. Object have attributes. These are the characteristic that describe the object . For ex a student object has the attributes like name, address, branch, semester etc. A book has the attributes like the title, Id, author, price etc. Object have operations or behavior. For ex student object has operations like applying for library account, writing exams etc. Theses all operations need the basic information like the student name, branch and semester. Therefore now a class can be defined as a generalized description of same of object having the same type of attributes and operations. A class is the blueprint from which individual objects are created. An object is the physical representation of a class. Objects can be created from a class blueprint. Creating a class: As we have seen earlier, a class can be created with the given syntax. 1)Class followed by class name followed by open and closed curly braces which define the start and end of a class. class SimpleClass{ public static void main(String[] args){ System.out.println(“ Dummy class “); } } 2) main is the function (called method in java ) from which the program execution starts. 3) void is the return type of the class. Since the main method doesn’t return any data type. 4) static keyword will covered in later chapters. 5) public is the access specifier, which make main method accessible from the external source. 6) System is a predefined class . 7) println method which print to the connected output device 8) out is the outputstream object which is the console. Declaring Objects:

We can create the object to this class as follows. Classname identifier = new classname(); Ex : SimpleClass obj = new SimpleClass(); Creating objects of a class is called instantiation. Here obj is called the object of the SimpleClass. New on the rightside of the statement will allocate memory to the obj . In this way we can create as many object as we want. SimpleClass obj1,obj2,obj3; Here obj1,obj2,obj3 are all the SimpleClass type variables which are not yet allocated memory. An object cannot be used to access the members of a class until it is allocated memory. Assigning object reference variables: Ex: Save as Test.java class Test{ int a =10; public static void main(String args[]){ Test obj1 =new Test(); System.out.println(“Value of a = “+obj1.a); //prints 10 Obj1.a = 20; Test obj2 = obj1; // object 2 is referencing object 1 System.out.println(“Value of a = “+obj2.a); //prints 20 } } Here obj2 is pointing to the memory location of obj1. This is called object variable referencing.

Introducing methods: Methods are the function which operate on the class data. Ex main is the method which does the operation of starting the program execution. Similarly the user can defines his own methods for implementing the objects functionality. Ex: Save as ReactangleArea.java class ReactangleArea{ public void area(double width, double height){ double areaOfRectangle = width * height; System.out.println(“Area of the rectangle = “+areaOfRectangle);

} public static void main(String[] args){ double w = 20.5; double h = 15.2; ReactangleArea obj = new ReactangleArea (); // creating object obj.area(w,h); // calling the area method. } }

Constructors: Constructor is a method which has the same name as the class name and doesn’t have the return type. Constructors are used to initialize the objects of a class. Ex: class ReactangleArea{ double width=height=0.0; public ReactangleArea() { // Constructor width = 1; height = 1 ; } public void area(){ double areaOfRectangle = width * height; System.out.println(“Area of the rectangle = “+areaOfRectangle); } public static void main(String[] args){ ReactangleArea obj = new ReactangleArea (); // creating object obj.area(); // calling the area method. } } Constructor with out any parameters is called the default constructor. The object creation process ReactangleArea obj = new ReactangleArea (); has the call to the class default constructor, which does the initilization. Parameterized constructors: Constructor with parameters are called parameterized constructors. class ReactangleArea{ public ReactangleArea (double width, double height){ double areaOfRectangle = width * height; System.out.println(“Area of the rectangle = “+areaOfRectangle); } public static void main(String[] args){ double w = 20.5;

double h = 15.2; ReactangleArea obj = new ReactangleArea (w,h); // creating object } }

Usage of static keyword: Both data and methods can be declared as static. If a data or a method is defined as static in a class, all the objects of that class share the same memory location, i.e. point to the same memory location. Every object created for a class point to different memory locations. So the data of can be different in different object for the same data variable say width. But static data or methods cannot have their memory located in the objects, i.e. the static fields are created and available even if there are no objects declared for a class. Note: Static methods can access only static data. Static data or methods in a class can be accessed by the class name. Ex: class ReactangleArea{ public static double width,height; public static void main( String[] args){ double area = width*height; // ( or ) double area = ReactangleArea.width * ReactangleArea.height ; } } class Area{ static void area(){ double area = ReactangleArea.width * ReactangleArea; } } One java program can consists of more than one class.

Usage of final with data: The final keyword can be used with data, methods & classes. The value of a final data of the class cannot be modified after it is once initialized. The final data members are like constants in java. Ex: public final double pi = 3.45; The operation defined by the final method of a class cannot be modified by its subclasses. Ex:

public final double rectangleArea(double width , double height){ double area = width * height; return area; } If a class is declared as final cannot be modified or extended by subclasses. If a class is final then all its members are by default final. Ex: final class Stack{ }

Access controls: All the data and the methods declared in a class are accessible in that class. If we want the members of a class to be accessible from another class we have to use the access specifiers. Theses are list of access specifiers used in java. public : Accessible from anywhere private : Accessible within the class only. protected : Accessible within same class and all the subclasses within the same and other packages default: : Members declared with no access specifier have the default access also called package access. These members are accessible to all the members in the same class and same package.

this Keyword: this reference refer to the current class object in which it is used. 1) If the name of the data member is the same as the name of the method parameter, then this reference can used to identify the current class member. 2) A class can add itself to list of various objects. Ex: class Student{ String name; public void setStudentName(String name){ this.name = name; } public void addStudentInfo(){ collegeInfo.add(this); } } this.name is the name data field declared in Student class.

Garbage collection: Java performs garbage collection for your programs, and thus eliminates the need to free objects explicitly. When no references exists to an object, and thus, the object becomes unreachable. Java can reclaim the memory allocated to that object, without you doing anything about it. Thus, java has the new operator, but there is no corresponding delete operator as in c++.

When you no longer want to reference an object, you can explicitly set its reference to null. Student s1 = new Student(); s1.setName(“Ravi”); … s1= null;

OverLoading Methods: In java, a class can have two or more methods with the same name but with different signatures. The signature of a method consist of the name together with the number and type of its parameters. This feature of having multiple methods with the same name but different signatures is known as overloading. The compiler identifies the method based on the number and type of parameters. Class FigureArea{ public void area(double width, double height){ System.out.println(“Area of rectangle = “+ width* height); } public void area(double size){ System.out.println(“Area of Square = “+ size* size); } public float area(float base, float height){ return 0.5*base* height; } public static void main(String args[]){ FigureArea fa = new FigureArea(); fa.area(23.4); // calls the 2nd area method fa.area(14.5f, 12.0f); // calls the 3rd area method fa.area(18.5, 12.5); // calls the 1st area method } }

Overloading constructors: Writing more than one constructor but with different signatures is the overloading of constructors.. Constructor doesn’t have the return type. Ex: Class FigureArea{ public FigureArea (double width, double height){ System.out.println(“Area of rectangle = “+ width* height); } public FigureArea (double size){ System.out.println(“Area of Square = “+ size* size);

} public FigureArea (float base, float height){ return 0.5*base* height; } public static void main(String args[]){ FigureArea fa1,fa2,fa3; fa1 = new FigureArea(23.4); // calls the 2nd area method fa2 = new FigureArea(14.5f, 12.0f); // calls the 3rd area method fa3 = new FigureArea(18.5, 12.5); // calls the 1st area method } }

Parameter passing – call by value:In java parameters are passed to methods by value. This means that a copy of the parameters that the calling code had supplied, is made and given to called method. The called method can make any changes to the value of the parameter received, but it will have no impact on the calling code. class PassByValue{ public static void main(String args[]){ int a=5; int b=6; System.out.println(“Before sorting”); System.out.println(“A is “ + a); System.out.println((“B is “+b); sort(a,b); System.out.println(“After sorting”); System.out.println(“A is “ + a); System.out.println((“B is “+b); } public static void sort( int x, int y){ int z = x; x = y; y = z; System.out.println(“Sorted”); System.out.println(“A is “ + a); System.out.println((“B is “+b); } }

If the parameter to a method is an object reference, then it is the object reference that is supplied “by value”. In the calling code the object reference will continue to refer to the same old object.

Nested Classes: A class can be nested inside another class. This means defining a class as a member of another class. This is done only when the nested class relies on the functionality of the outer class. Class LinkedList{ private Item top = null; private Item bottom = null; private class Item{ public int value; public Item next; public Item( int val, Item next) { value = val; this.next = next; } } public void insert(int val){ Item item = new Item(val, top); top = item; if(bottom == null) bottom = item; } // ….. } Nesting of classes beyond one level becomes difficult to read and understand.

Inner Class: Inner class is one type of nested class. An non-static nested class is called an inner class.

Exploring String Class: Strings in java are not primitive data types. a)Java has a predefined String class. So strings are objects are in java Creation of a String: 1) String s1 = new String(”Hello”); The string object s1 now points to memory location which holds the string literal “hello”; 2) String s2 = “ This is a string literal”; Any text enclosed within the double quotes is also a string.

3) String s3 = s1; Now the string object s3 is pointing to the same memory location which s1 is pointing. The difference between a string object and a string literal :String sa1 = new String (“Hello”); String sa2 = new String (“Hello”); String sb1 = “World”; String sb2 = “World”; Here sa1 and sa2 are same text string but are pointing two different memory locations. But since sb1 literal is created and memory is allocated to it, the sb2 will not create the new memory but will point to location where sb1 is pointing to. b)Strings are immutable.(Once string object is created its contents cannot be altered). String s1= new String(“Hello ”); s1 = s1+”World”; // this is called concatenation of strings. (or) s1+= “World”; Concatenating a new character or a string to existing string object , will first allocate new memory with new size(say here 11) and the string(here “Hello world”) is stored in it. So every time a concatenation happens the new memory location is created, which is a costly process. So java introduced StringBuffer class The StringBuffer class will have by default 16 characters of extra space allocated to it. so the concatenation process is not so costly. StringBuffer sb = new StringBuffer(“Hello”);

Related Documents

Unit Ii
November 2019 33
Unit Ii .pdf
October 2019 5
Uml Course Unit Ii
May 2020 4

More Documents from ""