OOPS-Unit 1.pdf
Document Details
Uploaded by PremierTsilaisite
University of Mumbai
Tags
Full Transcript
Rhucha SYCS-JAD Unit I Unit I Define OOPS - Object Oriented Programming OOP is a programming methodology that helps to arrange complex program through the us...
Rhucha SYCS-JAD Unit I Unit I Define OOPS - Object Oriented Programming OOP is a programming methodology that helps to arrange complex program through the use of some principles knows as OOP. The popular object-oriented language. Like Java, C#, PHP,python The main aim of object-oriented programming is to implement real-world. Class, Object, Data Abstraction, Inheritance, Polymorphism, Encapsultion. Security : OOP provide data hiding. Object : In OOP program is divided into parts What is a Class in Java? A class defines a new data type. A class is a template for an object. A class is declared by use of the class keyword. General Form class classname { type variable1; Fields Declaration type variable2; type methodname1() Method Declaration { body of method } } What are Objects in Java? Rhucha SYCS-JAD Unit I Objects is the variable of type class An object contains an address and takes up some space in memory. Objects can communicate without knowing the details of each other's data or code. A class provides the blueprint for objects; you create an object from a class. Syntax : ClassName ObjectName=new ClassName(); Each of the following statements creates an object. a) Rect rectOne = new Rect(); b) Rect rectTwo = new Rect(); The “.” dot operator is used to provide values to the instance variables. Also we can call some method of the class which will help us in setting the values of the object variables. Each of the above statements has three parts Declaration- a) Declaring a Variable to Refer to an Object: b) A variable declaration with a variable name with an object type. c) Rectangle rectTwo; d) Simply declaring a reference variable does not create an object. For that, you need to use the new operator. e) You must assign an object to rectTwo before you use it in your code. Otherwise, you will get a compiler error. Instantiation (Instantiating a Class): a) The new keyword is a Java operator use to creates the object b) The new operator returns a reference to the object it created. This reference is usually assigned to a variable of the appropriate type, like: c) Rect rectTwo = new Rect(); Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object Example of Class and Object class Rectangle //Class Declaration { public int length; //Class Variables public int breadth; int Area((int p, int q) //Class Methods { length=p; breadth=q; int ans=length*breadth; return (ans); } public static void main(String args[]) { Rectangle rectTwo= new Rectangle(); //Object Creation int ans=rectTwo.Area(10,20); System.out.println(“Area of rectangle=”+ans); } Rhucha SYCS-JAD Unit I } What is static keyword? When a member is declared static, it can accessed before any objects of its class are created, and without reference of any object. The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class. Static means only one copy exists The static can be: 1. variable (also known as class variable) 2. method (also known as class method) 3. block _________________________________________________________________________________ What is Java static variable? Java static variable If you declare any variable as static, it is known static variable. Only one copy of this variable exists It makes your program memory efficient (i.e it saves memory). The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc. Declaration of static variable static String collegenm =“Nirmala"; What is static method and static block? Java static method If you apply static keyword with any method, it is known as static method. A static method can be invoked without the need for creating an instance of a class. A static method is invoked with class name. A static method can access static data member and can change the value of it. A static methods can only call other static methods. They must only access static data. Java static block It is executed before main method at the time of classloading. Example of Static: class Student { static //Static Block { System.out.println("Static Block is invoked"); } static String clgName="Nirmala"; //static variable Rhucha SYCS-JAD Unit I static void change() //static method { clgName="Nirmala Foundation Memorial College"; } void Display() { System.out.println("College Name mis :"+clgName); } public static void main(String args[]) { Student.change(); Student s=new Student(); s.Display(); } } What is Constructor in java? Java supports a special type of method, called constructor, that enables an object to initialize itself when it is created. They do not specify a return type, not even void, because they return the instance of the class itself. It is a special type of method which is used to initialize the object. Constructor is invoked at the time of object creation Rules for creating constructor Constructor name must be same as its class name Constructor must have no explicit return type What are different types of constructor? Default constructor (no-arg constructor) a) A constructor is called "Default Constructor" when it doesn't have any parameter. b) Default constructor is used to provide the default values to the object like 0. c) Syntax (){} d) Example class Abc { Abc() { System.out.println("Abc is created"); } public static void main(String args[]) { Abc b=new Abc(); Rhucha SYCS-JAD Unit I } } Parameterized constructor a) A constructor which has a specific number of parameters is called parameterized constructor. b) Parameterized constructor is used to provide different values to the distinct objects. class Student4 { String name; Student4(String n) { name = n; } void display() { System.out.println(name); } public static void main(String args[]) { Student4 s1 = new Student4("sameera"); s1.display(); } } Explain Method Overloading in java? Methods that have the same name, but different parameter lists and different definitions are called method overloading. Method overloading is used when objects are requiredtob perform similartasks but using different input parameters. Method is called in an object, Java matches up the method name first andtype of parametersto decidewhich one of the definitions toexecute. This process is knownas polymorphism. Example class Room { float length,breadth; Room(float x, float y) { length=x; Breadth=y; } Room(float x) { Rhucha SYCS-JAD Unit I length=breadth=x; } float area() { return length*breadth; } public class RoomFull { Public static void main(String args[]) { Room r1=new Room (5,8); System.out.println(“Value of Room 1 is” +r1.area()); Room r2=new Room (4); System.out.println(“Value of Room 2 is” +r2.area()); } } Define this – keyword Sometimes a method will need to refer to the object that invoked it. Java defines the this keyword. this can be used inside any method to refer current object (class instance variable). this is a reference variable that refers to the current object. Example class TestStudent { int rno; String name; TestStudent(int rno, String name) { this.rno=rno; this.name=name; } void Display() { System.out.println(rno+" "+name); } public static void main(String args[]) { TestStudent ts=new TestStudent(11,"Rhucha"); ts.Display(); } } Rhucha SYCS-JAD Unit I What is inheritance in java? Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system). The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. We use inheritance: For Method Overriding (so runtime polymorphism can be achieved). For Code Reusability. Syntax: class Subclass-name extends Superclass-name { //methods and fields } Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class. Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class. The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality. The Sub class will now contain its own method and variables as well as those of superclass What are different types of Inheritance? Types of Inheritance: a) Single Inheritance: when one class inherits the only one super class b) Multilevel Inheritance: Derived from a derived class c) Hierarchical Inheritance: one super class and many sub classes d) In java programming, multiple and hybrid inheritance is supported through interface only. Rhucha SYCS-JAD Unit I Explain Single Inheritance. When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits the Animal class, so there is the single inheritance. Syntax: class subclassname extends superclassname { variable declaration; method declaration; } The keyword extends signifies that the properties of superclassname are extended to the subclassname. Explain the concept of Multilevel Inheritance. When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance. Syntax : class A { statements } class B extends A //First level { statements } class C extends B //Second level What is Subclass Constructor? Rhucha SYCS-JAD Unit I A subclass constructor is used to construct the instance variables of both the subclass and the superclass. It uses the keyword super to invoke the coonstructor method of the superclass. Following are the rules to use keyword super : 1) super may only be used within the subclass constructor method. 2) The call to superclass constructor must appear as the first statement within the subclass constructor. 3) The parameters in the super call must the order and type of the instance variable declared the superclass. What is concept of Overriding in Java and what are the rules of overriding? If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java. In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding. Method overriding is used to provide the specific implementation of a method which is already provided by its superclass. Method overriding is used for runtime polymorphism Rules for Java Method Overriding 1. The method must have the same name as in the parent class 2. The method must have the same parameter as in the parent class. 3. There must be an IS-A relationship (inheritance). Example class super { int x; Super(int x) { this.x=x; } void Display() { System.out.println("Super x="+x); } } class Sub extends Super { int y; sub (int x, int y) { super(x); this.y=y; } Rhucha SYCS-JAD Unit I void Display() { System.out.println("Super x="+x); System.out.println("Sub y="+y); } } class OverTest { public static void main(String args[]) { Sub s=new Sub(100,200); s.Display(); } } Inner Classes Java inner class or nested class is a class that is declared inside the class or interface. Inner classes are used to logically group classes and interfaces in one place to be more readable and maintainable. Additionally, it can access all the members of the outer class, including private data members and methods. Syntax of Inner class class Java_Outer_class { //code class Java_Inner_class { //code } } Example class Outer { int outer_x=100; void test() { Inner inner=new Inner(); inner.display(); } class Inner //inside outer class { void display() { System.out.println("Display outer_x :"+outer_x); Rhucha SYCS-JAD Unit I } } } class IOClassDemo { public static void main(String args[]) { Outer ot=new Outer(); ot.test(); } } Write difference between Method Overloading and Method Overriding in java. No Method Overloading Method Overriding Method overriding is used to provide the specific Method overloading is used to increase the 1 implementation of the method that is already readability of the program. provided by its super class. Method overloading is performed within Method overriding occurs in two classes that have 2 class. IS-A (inheritance) relationship. In case of method overloading, parameter In case of method overriding, parameter must be 3 must be different. same. Method overloading is the example Method overriding is the example of run time 4 of compile time polymorphism. polymorphism. What is Polymorhism? Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Polymorphism in Java has two types: Compile time polymorphism (static binding) and Runtime polymorphism (dynamic binding). Method overloading is an example of static polymorphism, while method overriding is an example of dynamic polymorphism. What is Abstraction? Abstraction is a process of hiding the implementation from the user, only the functionality is exposed here. So it’s only of what the application does, not how it does it. In that way data is hidden inside object and is only accessible through object. Rhucha SYCS-JAD Unit I Abstraction is the process of abstraction in Java which is used to hide certain details and only show the essential features of the object. In other words, it deals with the outside view of an object (interface). For example, TV remote is an object. Users are provided with only interface which is nothing but keys. Users only know which key to press for what function. User will not know what happens inside when we press the key. Same is the case in Java. Abstraction is achieved with the help of interface. Interface expose only methods to end users Explain abstract class and abstract methods. Abstract Class A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract and non-abstract methods (method with the body). An abstract class must be declared with an abstract keyword. It can have abstract and non-abstract methods. It cannot be instantiated. It can have constructors and static methods also. It can have final methods which will force the subclass not to change the body of the method. Syntax: abstract class A{} Abstract Methods A method which is declared as abstract and does not have implementation is known as an abstract method. Example: abstract void printStatus();//no method body and abstract Example: abstract class Abc { abstract void method1(); } class Xyz extends Abc { void method1() { System.out.println("running safely"); } } public static void main(String args[]) { Xyz obj = new Xyz(); obj.method1(); } } Example of Abstract class and method Rhucha SYCS-JAD Unit I abstract class Language //abstract class declaration { abstract void write(); //abstract method declaration public void display() { System.out.println("This is Java Language"); } } class Java extends Language { // provide implementation of abstract method public void write() { System.out.println("print a statement"); } } class JavaMain { public static void main(String args[]) { // create an object of Java class Java jv = new Java(); jv.write(); jv.display(); } } What is Encapsulation? Encapsulation binds together the data and functions that manipulate the data, keeping it safe from interference and misuse. Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. Thus encapsulation is said to be providing “access control” through which we can control which parts of the program can access the members of any class and thus prevent misuse. Various access controls are public, private and protected. Rhucha SYCS-JAD Unit I The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code. Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. It is actually the process of binding data members and methods together in a unit.Each class in java itself is an example of encapsulation Example of Encapsulation class Person { // private field private int age; // getter method public int getAge() { return age; } // setter method public void setAge(int age) { this.age = age; } } class Details { public static void main(String args[]) { // create an object of Person Person p = new Person(); // change age using setter p.setAge(24); // access age using getter System.out.println("My age is " + p.getAge()); } } Rhucha SYCS-JAD Unit I What are Interfaces in java? Like Classes interface contains methods and variables but with a major difference, the difference is that interface defines only abstract methods and final fields The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritances in Java. In other words, interfaces can have abstract methods and variables. It cannot have a method body. Java Interface also represents the Inheritance relationship. It cannot be instantiated just like the abstract class. Interface declaration a) An interface is declared by using the interface keyword. b) It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. c) A class that implements an interface must implement all the methods declared in the interface. d) Syntax: interface { // declare constant fields // declare methods that abstract // by default. } Example interface Polygon { void getArea(int length, int breadth); } class Rectangle implements Polygon // implement the Polygon interface { public void getArea(int length, int breadth) // implementation of abstract method { System.out.println("The area of the rectangle is " + (length * breadth)); } } class Shape { public static void main(String args[]) { Rectangle r = new Rectangle(); r.getArea(5, 6); } }