Java Class and Object Concepts PDF

Summary

This document provides lecture notes for a course on Java programming. Topics covered include classes, objects, methods, and constructors, presented in a clear format suitable for beginners.

Full Transcript

Class and Object Lecturer Jasiya Fairiz Raisa 1 What is Class in Java? A class in Java is a set of objects which shares common characteristics/ behavior and common properties/ attributes. It is a user-defined prototype from which objects are created....

Class and Object Lecturer Jasiya Fairiz Raisa 1 What is Class in Java? A class in Java is a set of objects which shares common characteristics/ behavior and common properties/ attributes. It is a user-defined prototype from which objects are created. A Class in Java can contain: Data member Method Constructor Nested Class Interface 2 Object in Java An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It can be physical or logical. Anobject has three characteristics: state: represents data (value) of an object. behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc. identity: Object identity is typically implemented via a unique ID. Object is an instance of a class. Class is a template or blueprint from which objects are created. So object is the instance(result) of a class. 3 Class declaration A class is a template for manufacturing objects. You declare a class by specifying the class keyword followed by a non-reserved identifier that names it. A pair of matching open and close brace characters ({ and }) follow and delimit the class's body. 4 Naming Convention Class names, method names and variable names are all identifiers and by convention all use the same camel case naming scheme. Also, by convention, class names begin with an initial uppercase letter, and method names and variable names begin with an initial lowercase letter. 5 Instance Variables of Class Instance variables are declared inside a class declaration but outside the bodies of the class’s methods. Instance variables implement the attributes of an object throughout its lifetime. Each object (instance) of the class has its own copy of the class’s instance variables. Instance variables exist before methods are called on an object, while the methods are executing and after the methods complete execution A class normally contains one or more methods that manipulate the instance variables belonging to particular objects of the class. 6 Constructors Constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. Constructors can also take parameters, which is used to initialize attributes. Note that the constructor name must match the class name, and it cannot have a return type. Also note that the constructor is called when the object is created. All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes. 7 Constructors // Create a class named ‘Main’ public class Main { int x; // Create a class attribute // Create a class constructor for the Main class public Main() { x = 5; // Set the initial value for the class attribute x } public static void main(String[] args) { Main myObj = new Main(); // Create an object of class Main (This will call the constructor) System.out.println(myObj.x); // Print the value of x } } 8 Constructors public class Main { int x; public Main(int y) { x = y; } public static void main(String[] args) { Main myObj = new Main(5); System.out.println(myObj.x); } } 9 Multi-class applications and main() A Java application is implemented by one or more classes. Small applications can be accommodated by a single class, but larger applications often require multiple classes. In that case one of the classes is designated as the main class and contains the main() entry-point method. 10 A Simple Class As stated, a class defines a new type of data. In this case, the new data type is called Box. will use this name to declare objects of type Box. It is important to remember that a class declaration only creates a template; it does not create an actual object. Toactually create a Box object, you will use a statement like the following: Box mybox = new Box(); // create a Box object called mybox The new keyword is used to allocate memory at runtime 11 A Simple Class Each time you create an instance of a class, you are creating an object that contains its own copy of each instance variable defined by the class. Thus, every Box object will contain its own copies of the instance variables width, height, and depth. Toaccess these variables, you will use the dot (.) operator. The dot operator links the name of the object with the name of an instance variable. For example, mybox.width = 100; 12 Declaring Objects you must acquire an actual, physical copy of the object and assign it to that variable. You can do this using the new operator. The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns a reference to it. This reference is, more or less, the address in memory of the object allocated by new. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated. 13 Declaring Objects To declare anobject of type Box: mybox = new Box(); Thisstatement combines the two steps just described. It can be rewritten like this to show each step more clearly: Box mybox; // declare reference to object mybox = new Box(); // allocate a Box object 14 Here is a complete program that uses the Box class 15 Simple Example of Object and Class The new keyword is used to allocate memory at runtime 16 Example of Object and class that maintains the records of students 17 3 Ways to initialize object By reference variable By method By constructor 18 Initialize by Reference variable class Student{ int id; String name;} class TestStudent3{ public static void main(String args[]){ //Creating objects Students1=newStudent(); Students2=newStudent(); Output: //Initializing objects 101 Rahim s1.id=101; 102 Samia s1.name=“Rahim"; s2.id=102; s2.name=“Samia"; //Printing data System.out.println(s1.id+""+s1.name); }} System.out.println(s2.id+""+s2.name); 19 Initialization by method class Student{ private int rollno; String name; void insertRecord(int r, String n){ rollno=r; name=n;} void displayInformation(){System.out.println(rollno+" Output: "+name);}} 101 Rahim class TestStudent4{ 102 Samia public static void main(String args[]){ Student s1=new Student(); Student s2=new Student(); s1.insertRecord(101,“Rahim"); s2.insertRecord(102,“Samia"); s1.displayInformation(); s2.displayInformation(); }} 20 Initialization by constructor class Student { int id; String name; Student(int id, String name) { this.id = id; this.name = name; }} Output: 101 Rahim class TestStudent3 { public static void main(String args[]) { 102 Samia Student s1 = new Student(101, "Rahim"); Student s2 = new Student(102, "Samia"); System.out.println(s1.id + " " + s1.name); System.out.println(s2.id + " " + s2.name); } } 21 Creating multiple objects by one type only Each object has its own copies of the instance variables. This means that if you have two Box objects, each has its own copy of depth, width, and height. is important to understand that changes to the instance It variables of one object have no effect on the instance variables of another. 22 Creating multiple objects by one type only 23 Creating multiple objects by one type only 24 Assigning Object Reference Variables Box b1 = new Box(); Box b2 = b1; You might think that b2 is being assigned a reference to a copy of the object referred to by b1. That is, you might think that b1 and b2 refer to separate and distinct objects. However, this would be wrong. Instead, after this fragment executes, b1 and b2 will both refer to the same object. The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the same object as does b1. Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since they are the same object. 25 Methods The general form of a method: Here, type specifies the type of data returned by the method. This can be any valid type, including class types that you create. If the method does not return a value, its return type must be void. The name of the method is specified by name. The parameter-list is a sequence of type and identifier pairs separated by commas. 26 Volume method does not return a value 27 Volume method returns a value 28 Adding a method that takes parameters 29 What are the differences between constructor and method in java? 30 Difference between constructor and method in java 31 Parameterized Constructor class Box { double width; double height; double depth; // This is the constructor for Box. Box(double w, double h, double d) { width = w; height = h; depth = d; } // compute and return volume double volume() { return width * height * depth; }} 32 Multiple Constructor A class can have multiple constructors, given that the syntax / signature of the constructors are different. Here signature means the type and number of parameters in the constructor. All constructors will have same name. This concept is known as CONSTRUCTOR OVERLOADING. Class Box{ Box(double w){ width = w; } Box(double w, double l){ width = w; length = l; } } 33 Object as Parameter Object can be passed as parameter in a method. This can be done in two different ways: Call by value Call by reference 34 Call by value // Simple Types are passed by value. class Test { int a, b; void mtd(inta, int b) { a+= 2; Output: b+= 2; }} a and b before call: 15 20 a and b after call: 15 20 class CallByValue { public static void main(String args[]) { Test ob= new Test(); int a = 15, b = 20; System.out.println("a and b before call: " + ob.a+ " " + ob.b); ob.mtd(a, b); System.out.println("a and b after call: " + ob.a+ " " +ob.b); }} 35 Call by reference class Test { int a, b; // pass an object void mtd(Test o) { o.a+ = 2; o.b+ = 2; }} class CallByRef{ public static void main(String args[]) { Test ob= new Test(); System.out.println("ob.a and ob.b before call: " + ob.a+ " " + ob.b); ob.mtd(ob); System.out.println("ob.a and ob.b after call: " +ob.a+ " " + ob.b); }} Output: ob.a and ob.b before call: 0 0 ob.a and ob.b before call: 2 2 36 Returning object class Test { int a; Test(int i) {a = i;} Test incrByTen() { Test temp = new Test(a + 10); return temp; }} Output: class RetOb { ob1.a: 2 public static void main(String args[]) { ob2.a: 12 Test ob1 = new Test(2); Test ob2; ob2 = ob1.incrByTen(); ob2.a after second System.out.println("ob1.a: " + ob1.a); increase: 22 System.out.println("ob2.a: " + ob2.a); ob2 = ob2.incrByTen(); System.out.println("ob2.a after second increase: " + ob2.a); } } 37 Introduction to Access Modifiers The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class. There are 4 types of java access modifiers: private default protected public 38 Introduction to Access Modifiers Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default. Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package. 39 Thank you 40

Use Quizgecko on...
Browser
Browser