Cs - Unit1 2nd Half

You might also like

Download as pdf
Download as pdf
You are on page 1of 27
MNT ON r features of Constructor: F Constructors are invoked implicitly when you instantiate objects / A Java constructor name must exactly match with the class name (includi: case) and must not have a return type. If a class doesn’t have a constructor, Java compiler automatically creates default constructor during run-time. The default constructor initiali, instance variables with default values. For example: int variable will ) initialized to 0 ¥ Constructors cannot be abstract or static or final. ¥ Constructor can be overloaded but can not be overridden. >rogram to show usage of constructor class ConsMain { * The us 4 i o . private int x; ey : : /} constructor private ConsMain() { Spent Cir rat es x=5; public stticvoid main Sting] args) j ‘ ConsMain obj = new ConsMainQ; System.out printin(’Value ofx="+ ae ) ) 2 Output: Constructor Called Value of x =5 Here, ConsMain() constructor is called when obj object is instantiated. / constructor may or may not accept arguments. If the object is created outside of the class, you have to declare the construct? public to access it. NIT ONE 1.35 parameterized Constructor: A constructor that accepts parameters is called as Parameterized Constructor. Depending upon the argument passed, parameterized constructor is called. Syntax: accessModifier ClassName(arg]1, arg?, ..., argn) { // constructor body { Program to show usage of parameterized constructor class Vehicle { int wheels; private Vehicle(int wheels) t _ wheels = wheels; System.out printin(wheels +" wheeler vehicle created."); } public static void main(String[] args) { Vehicle v1 = new Vehicle(2); Vehicle v2 = new Vehicle(3); Vehicle v3 = new Vehicle(4); } } Output: 2 wheeler vehicle created. 3 wheeler vehicle created. 4 wheeler vehicle created. In above program, we have passed an argument of type int (number of wheels) to the constructor during object instantiation. 1.1.17 Constructor Overloading Similar to method overloading, you More constructors are different in parameters. : can also overload constructors if two or In java, garbage means ; reclaiming the runtime un UNIT ONE 1.37 But, in java it is performed automatically. Hence, java provides better memory management. Advantage of Garbage Collection - (1) It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory. (2) It is automatically done by the garbage collector(a part of JVM) so we don’t need to make extra efforts. There 3 many ways in which an object can be unreferenced - (1) By nulling the reference - Example, : Employee e=new Employee(); esnull; (2) By assigning a reference to anomie - eg Employee el=new Employee(); > Employee e2=new Employee(); el=e2;//now the first object referred by el is available a garbage collection : ; @ By annonymous object etc - Sag eerie a new Employee); m finalize() method: The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. Syntax: Protected void finalize &e() method: The gc() method is used to invoke the garbage collector to perform cleanup Processing. The gc() is found in System and Runtime classes. Syntax: _publicstatic void get). Output is garbage collected . : ds-static Keyword ods are also called as class members variables and meth a class member in Java, en you have t (variables 2 ! you must firs ‘0 define The static methods). Normally, if you want to create an instance of the class. But, there will be cases wh ating an instance dass member that will be used independently without cre However, in Java that can be to to create such a member, member. Class Variable (Static variable): Static variable in Java is variabl i once at the start of the execution. which Eelangner class and initialized of th itis possible to create a class members (variables and methoc: and invoked without creating an instance of the class. In ors you have to use static keyword while declaring + clas on Syntax: static ; ‘ Example, static int count; le which belongs to the class and not to object(instance). at the start of the execution. These tion of any instance jg a variab! variables are initialized only once, bles will be initialized first, before the initializal bles. le copy to be shared by all instances of the class. need . static variable can be accessed directly by the class name and doesn’t usage of static variable: there are 500 students ina college, below is class declaration. ANE é ers will get memory each time when object is and name so instance data member is of all objects. If we make it static, rogram we declare the “String instance data memb ‘student have its unique rollno college refers to the common property only once. The below p get memory as static and create two objects $1 and s2. uNIT ONE ¥ Itisa method which belongs to the class and not to the object(instance). 1.41 ¥ A static method can access only static data. It can not access non-static data (instance variables). Y A static method can call only other static methods and can not call a non- static method from it. ¥ A static method can be accessed directly by the class name and doesn’t need any object. Y Astatic method cannot refer to "this" or "super" keywords in anyway. Program to show usage of static method: / /Program | for changing the common property of all objects (static field). class Student C= eatin; . String name; ae "TIS"; ey college = "BBDIT"; Ee ; Student(int r, String n) ie : : rollno =r; name = n; fee void eles 0 {3 ‘Systema printin(rollnot" "+namet+" "+college); static void main(String args|]) ‘Student.change(); Student s1 = new Student (111,"Karan’); Student s2 = new Student (222,"Aryan"); _ Student s3 = new Student (333,"Sono0"); sl.display(); . _ s2.display(); sdieplay)) 111 Karan BBDIT _ 222 Aryan BBDIT 333 Sonoo BBDIT 1.1.20 this Keyword eed es In java, “this” is a reference variable that refers to the current object. Usage of “this” keyword: ° ‘ ‘ : (1) this can be used to refer current class instance variable. (2) this can be used to invoke current class method (implicitly). 3), this() can be used to invoke current class constructor. variable Object . > this: to refer current class instance variable: The this keyword can be used to refer current class instance variable. If there ! ambiguity between the instance variables and Parameters, this keyword resolves th problem of ambiguity. If local variables (formal arguments) and instance variable are different, there is no need to use “this” keyword.’ Program to show usage of “this” to refer current class instance variable: class Student int rollno; String name; float fee; , Student(int rollno String name,float fee) uniT ONE __ 1.43 intIn(rollno+" "+name+" "+fee); 111 ankit 5000.0 112 sumit 6000.0 to invoke current class method: nay invoke the method of the current class by using the this keyword. If e the this keyword, compiler automatically adds this keyword while ey UN My, Methog, class ca 3 1.45 tic void main(String args|]) A(10); helloa 10 1.1.21 One-Dimensional Arrays Array is a collection of similar type of elements that have contiguous memory location. Java array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in ajava array. Array is index based, first element of the array is stored at 0 index. Element (at index 8) First Index -_—— Array length Is Advantage of Array: Y Code Optimization: It makes the code optimized, we can retrieve or sort the data easily. Y Random access: We can get any data located at any index position. Disadvantage of Java Array: Y Size Limit: We can store only fixed size of elements in the array. It doesn’t grow its size at runtime. 4.089 ¥ , UNIT a There are two types of array - (1) Single Dimensional Array (2) Multidimensional Array Single Dimensional Array: A single-dimensional array is the simplest form of an array that Fequires ,, one subscript to access an array element. A one-dimensional array (o; sin, dimension array) is a type of linear array. Declaration of an single dimensional array in java - Syntax: : dataType[larr; (er) dataType arr{]; Instantiation of an Arrayan in java - Syntax: alt}-20; ae a{2]=70; # a[3]=40; a[4]=50; //printing, array for(int i=0; i java TestCommandline Hello World Output: Hello World 1.1.24 Inner Class Java inner class or nested class is a class which is declared inside the class © interface. We use inner classes to logically group classes and interfaces in one plac so that it can be more readable and maintainable. Additionally, it can access all th members of outer class including private data members and methods. 1.49 There are two types of nested classes you can create in Java. (1) Non-static nested (inner class) (2) Static nested class Non-static nested class are also called as inner class. Key points: ¥ Java treats inner class as a regular member of a class. They are just like methods and variables declared inside a class. Y Since, inner class are members of outer class, you can apply any access modifiers like private, protected to your inner class which is not possible in normal classes. Since Nested class is a member of its enclosing class Outer, you can use . (dot) ‘notation to access Nested class and its members. ¥ Using nested class will make your code more readable and provide better encapsulation. ¥ Non-static nested classes (inner classes) have access to other members of the ‘outer/enclosing class, even if they are declared private. Program to show usage of inner class: ARE ee oe 1.50 UNIT 180) pee eee return 4.2; ! } protected class RAM. { double memory; String manufacturer; double getRAMSize() ( return 5.5; ) public class TestInnerclass { j public static void main(String|] args) { te CPU cpu = new CPU); CPU Processor processor = cpu.new Processor(); CPU.RAM ram = cpu.new RAM(); System.out.println("Processor Speed =" + processor, i pelroceseoSpeed(); System.out.printin(" Ram Size =" + ram.getRAMSize()); t } } Output: Processor Speed = 4.2 Ram Size =5.5 In above program, the class CPU encapsulates two inner classes i.e. Proce~ and RAM. Since, the class RAM is inner class you can declared it as protected. In ' Main class, the instance of CPU is created at first. And in order to create the inst’ of Processor, the . (dot) operator is used. CPU.Processor Processor = cpunew Processor(); MEQ WHeritTance 1.2.1 Introduction Inheritance is one of the key features of Object Oriented Program ; Inheritance provided mechanism that allowed a class to inherit property of anol" : | ww i UNIT ONE 1.51 When a Class extends another class it inherits all non-private members oeuding fields and methods. Inheritance in Java can be best understood in terms of a and Child relationship, also known as Super class (Parent) and Sub class (aiild) in Java language. 1.2.2 Types of Inheritance On the basis of class, there can be three types of inheritance in java: (1) Single Q) Multilevel (3) Hierarchical Multiple inheritance is not supported in java through class. > Single Inheritance: In Single Inheritance one class extends another class (one class only). Figure: Single Inheritance In above diagram, Class B extends only Class A. Class A is a super class and Class B is a Sub-class. > Multilevel Inheritance: In Multilevel Inheritance, one class can inherit from a derived class. Hence, the derived class becomes the base class for the new class. Figure: Multilevel Inheritance ne above diagram, Class C is subclass of B and Bisa of subclass Class A. > Hierarchical Inheritance: In Hierarchical Inheritance, one class is inherited i many sub classes. Figure: Hierarchical Inheritance In the above diagram, Class B and C inherit the same class A. 1.2.3 extends Keyword Examples ) Inheritance defines is-a relationship between a Super class and its Sub cle. extends and implements keywords are used to describe inheritance in Java. From the above example we can say - Y Vehicle is super class of Car. _ Y Car is sub class of Vehicle, Y Car IS-A Vehicle. Program to show usage of "Car"; _//accessing Vehicle class member "sports tIn(modelType+" "+vehicleType); id main(String|] args) of Inheritance - motes the code reusabilty i.e the same methods and variables which are in a parent/super/base class can be used in the child/sub/ derived olymorphism by allowing method overriding. d Overriding ss has same name, same number of arguments and ‘method in a sub cla: enature as a method in its super class, then the method is known as en method. Method overriding is also referred to as runtime polymorphism. t of overriding is the abitility to define method that’s specific to a ‘method must have same name as in the parent class. od must have same parameter as in the parent class. IS-A relationship (inheritance). Program to show method overriding: : : ¥ public void eat() { System.out.printin("Generic Animal eating"); public void eat() // eat() method overriden by Dog class. Dog eat meat In the above program, you can see the Dog class gives it own implementation o eat() method. 1.2.5 super Keyword We can use super keyword to access the data member and method of pare? class. It is used if parent class and child cl; ass have same fields and methods. Program to show u: ( f »- String color="white'; sage of super keyword: alin rogram to show method overriding: ass Animal public void eat() { System.out.printin("Generic Animal eating"); ' : 4 ass Dog extends Animal public void eat() //eat() method overriden by Dog class. Be { RG System.out-printin("Dog eat meat"); public static { void main(String args[]) Dog d = new Dog() deat); — } Ie dutput: Dog eat meat In the above program, you can see the Dog class gives it own implementation 0 at() method. 2.5 super Keyword The super keyword in java is a reference variable which is used to refe’ We can use super keyword to access the data Member and method of pare! lass. It is used if Parent class and child class have same fields and methods. rogram to show usage of super keyword: 5 String color="Wwhite"; in("Animal - eating..." lor); //prints color of Dog class +super.color); //prints color of Animal . UNIT oy, Dog color brown Animal color white jis tet on prop in te ee ep we call aes be D. Sate ol og, clas’ eat ae the color of Dog ¢ aa ey 2 default because priority is given to parent class method, we need to use supe! mal and rint colo property of call the ea! final keyword 1.2.6 final Keyword : restrict the user. The java The final keyword in java is used to be applied with » Variables » Methods » Classes 1. final variable: If you make any variable as final, you cannot change the value of final variabl: will be constant. Program to show dassBike { usage of final variable: final int speedlimit-90,/ final variable void run) error: cannot asi; ign a vali : - speedlimit=400; ue to final variable speedlimit 1.59 tract class can extend another An interface can extend another Java sand implement multiple Java interface only, class can be extended ; An interface class can be implemented yword extends. using keyword implements. Members of a Java interface are public by default, Example: public interface Drawable { void draw(); default, public and abstract Bee pte mpleainton ad method of interface A mp ements A : outprintin("I am a"); , final ifyou make any method as final, you cannot override it. program to show usage of final method: ; UNIT 9, System.outprintin(“running"); X ) } class Honda extends Bike { . void runQ) { System.out printin("running safely with 100kmph"); } public static void main(String args[]) { Honda honda= new Honda(); honda‘run(; _ ee 1 Lbs Ss . Output: error: cannot inherit from final Bike class Honda extends Bike a 1.2.7 Abstract Classes Verses Interfaces Abstract class and interface both are used to achieve abstraction where we ca: declare the abstract methods. Abstract class and interface both can’t be instantiated The differences between abstract class and interface as given below — pe ea (3) Abstract class can have final, Non-final, static and non-static variables, (4) Abstract class can Provide — the | Ini implementation of interface. jee (5) The abstract keyword | is used declare abstract class. e an‘t provide the | of abstract class. : :

You might also like