Object-Oriented Programming - Revature

¡Supera tus tareas y exámenes ahora con Quizwiz!

Constructor vs. Method

*Constructor*: A constructor is used to initialize the state of an object. - A constructor must not have a return type. - The constructor is invoked implicitly. - The Java compiler provides a default constructor if you don't have any constructor in a class. - The constructor name must be same as the class name. *Method*: A method is used to expose the behavior of an object. - A method must have a return type. - The method is invoked explicitly. - The method is not provided by the compiler in any case. - The method name may or may not be the same as the class name.

Method Overloading vs. Method Overriding (Polymorphism)

*Method Overloading* (same class, same method name, different parameters) - is used to increase the readability of the program. - is performed within class (multiple of the same method name and function, but different number of arguments or different data types) - same method name, same class, different parameters - method overloading is the example of compile time polymorphism (taking many forms) - can't be performed by changing return type of the method only - return type can be same or different in method overloading. But you must have to change the parameter *Method Overriding* (different classes, same method) - is used to provide the specific implementation of the method that is already provided by its super class - occurs in 2 classes that have IS-A (inheritance) - in case of method overriding, different classes, same parameters

Terms Used in Inheritance

- *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. - *Reusability*: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class. *Syntax* class Subclass-name *extends* Superclass-name { //methods and fields added here } 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. *Example of Inheritance* : The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee. class Employee{ float salary=40000; } class Programmer extends Employee{ int bonus=10000; public static void main(String args[]){ Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); } }

Dynamic vs. Static Language

- A *dynamic language (Lisp, Perl, Python, Ruby)* is designed to optimize programmer efficiency, so you can implement functionality with less code. - A *static language (C, C++, etc)* is designed to optimize hardware efficiency so that the code you write executes as quickly as possible.

Method Overriding (Polymorphism)

- If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.

Advantages of Object Oriented Programming vs. Procedure Oriented Programming

- OOPs makes development and maintenance easier if code grows as project size increases. - OOPs provides data hiding whereas in a procedure-oriented programming language a global data can be accessed from anywhere

Object-Oriented Programming

- a methodology or paradigm to design a program using classes and objects. - it simplifies software development and maintenance by providing some concepts: 1) Object 2) Classes 3) Inheritance 4) Polymorphism 5) Abstraction 6) Encapsulation

Advantages of Inheritance

- for method overriding (so runtime polymorphism can be achieved) - for code reusability

Inheritance

- is a mechanism in which one object acquires all the properties and behaviors of a parent object. - you can create new classes that are built upon existing classes. - you can reuse methods and fields of the parent class - you can add new methods and fields in your current class also - represents the parent-child relationship

Encapsulation

- wrapping code and data together into a single unit, for example, a capsule which is mixed of several medicines - we can create a fully encapsulated class in Java by *making all the data members of the class private - we can use setter and getter methods to set and get the data in it* - Java Bean class is an example of a fully encapsulated class *Advantages* - by providing only setter or getter methods, you can make the class *read-only or write-only* (so you can skip the getter or setter methods if you want) - it provides you *control over the data* - for example, you can write logic to set the value of id (which should be greater than 100 only) in the setter method - a way to achieve *data hiding* because other classes will not be able to access the data through the private data members - *easy to test*, so it's better for unit testing *Example* package com.revature; public class Student{ //private data member *private String name;* //getter method for name public String getName(){ return name; } //setter method for name public void setName(*String name*){ this.name=name } } //A Java class to test the encapsulated class. package com.revature; class Test{ public static void main(String[] args){ //creating instance of the encapsulated class Student s=new Student(); *//setting value in the name member * *s.setName("vijay");* *//getting value of the name member* *System.out.println(s.getName());* } }

Read-Only Class (Encapsulation)

//A Java class which has *only getter methods* public class Student{ //private data member private String college="AKG"; //getter method for college public String getCollege(){ return college; } } The above class is an example of a Read-Only class because it has only a getter to access the college name. If the user tries to change the value of the college name, a compile-time error is rendered.

Write-Only Class (Encapsulation)

//A Java class which has *only setter methods* public class Student{ //private data member private String college; //getter method for college public void setCollege(String college){ this.college=college; } } The above class is an example of a Write-Only class because it has only setters to change the value of the college name and cannot read the college name. Even if tried to access outside of this class a compile-time error is displayed only because the variable is declared as private.

Access Modifiers (Encapsulation)

1) *Access Modifiers* = specifies accessibility (scope) of a data member, method, constructor or class - private = within class ONLY - default = within class and within package ONLY - protected = within class, within package, and outside package by subclass ONLY - public = within class, within package, outside package 2) *Non-Access Modifiers* - static - abstract - synchronized - native - volatile - transient

Types of Constructors

1) *Default Constructor* - If there is no constructor in the class, the compiler adds a default constructor. - No-Argument Constructor = it contains a default call to super(); which is the default behavior public Bicycle() { gear = 1; cadence = 10; speed = 0; } Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike. 2) *Parameterized Constructor* - A constructor which has a specific number of parameters is called a parameterized constructor. The parameterized constructor is used to provide different values to the distinct objects. class Student4{ int id; String name; Student4(int i,String n){ id = i; name = n; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ *Student4 s1 = new Student4(111,"Karan");* *Student4 s2 = new Student4(222,"Aryan");* s1.display(); s2.display(); } } In the above example, we have created the constructor of Student class that have two parameters.

Types of Inheritance

1) *Single* 2) *Multilevel* 3) *Hierarchal* 4) *Multiple* (supported thru interface only) - not supported by java to reduce the complexity and simplify the language 5) *Hybrid* (supported thru interface only)

Ways to Achieve Abstraction?

1) Abstract class (0 to 100%) 2) Interface (100%)

Rules to Remember for Constructors

1) Constructor name must be the same as its class name 2) A Constructor must have NO explicit return type 3) A Java constructor CANNOT be abstract, static, final, and synchronized

OOP Pillars

1) Inheritance 2) Polymorphism 3) Encapsulation 4) Abstraction

Abstract Method

A method which is declared as abstract and does not have implementation is known as an abstract method. - abstract void printStatus(); //no method body and abstract *Example* abstract class Bike{ // Abstract class abstract void run(); // Abstract method } class Honda4 extends Bike{ *void run(){System.out.println("running safely");}* //this is placed here instead of as a method in the superclass Bike; so this means that the abstract method IS NOT instantiated public static void main(String args[]){ Bike obj = new Honda4(); obj.run(); } }

Constructor Overloading

A technique of having more than one constructor with different parameter types/lists - They are arranged in a way that each constructor performs a different task. class Student5{ int id; String name; int age; //creating two argument constructor *Student5(int i,String n)*{ id = i; name = n; } //creating three argument constructor *Student5(int i,String n,int a)*{ id = i; name = n; age=a; } void display(){System.out.println(id+" "+name+" "+age);} public static void main(String args[]){ Student5 s1 = new Student5(111,"Karan"); Student5 s2 = new Student5(222,"Aryan",25); s1.display(); s2.display(); } }

Object

Any entity that has states (attributes) and behavior is known as an object. (i.e. pen, bike, chair, table) - 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. - The only necessary thing is the type of message accepted and the type of response returned by the objects. . Example: A dog is an object because it has states (attributes) like color, name, breed, etc. as well as behaviors like wagging the tail, barking, eating, etc.

Abstract Class

It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated (create an instance of an object). - 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. (*static methods are used so that we don't need to create an instance for calling methods*) - It can have final methods which will force the subclass not to change the body of the method.

Constructors

It is a special type of method which is used to initialize the object and does not have a return type - When an object is created, the compiler makes sure that constructors for all of its sub-objects (its member and inherited objects) are called.

Can a Static Method be Overridden? (Polymorphism)

No, a static method cannot be overridden. It can be proved by runtime polymorphism. - static method is bound with class (belongs to the class area) - instance method is bound with an object (belongs to the heap area)

Class

Templates that are used to create objects, and to define object data types and methods. - Core properties include the data types and methods that may be used by the object. - A blueprint from which you can create an individual object. public class Dog { String breed; int age; String color; void barking() { } void hungry() { } void sleeping() { } }

Why Multiple Inheritance Is Not Supported in Java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java. - Java renders compile-time error if you inherit 2 classes - Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class. class A{ void msg(){System.out.println("Hello");} } class B{ void msg(){System.out.println("Welcome");} } class C extends A,B{ //suppose if it were public static void main(String args[]){ C obj=new C(); obj.msg(); //Now which msg() method would be invoked? } }

Usage and Rules for Method Overriding (Polymorphism)

Usage: - used to provide the specific implementation of a method which is already provided by its parent class - used for runtime polymorphism Rules: - the method must have the same name as in the parent class - the method must have the same parameter as in the parent class - there must be an IS-A relationship (inheritance) - parent-child relationship

Example of Method Overriding (Polymorphism)

class ABC{ //Overridden method public void disp() { System.out.println("disp() method of parent class"); } } class Demo extends ABC{ //Overriding method public void disp(){ System.out.println("disp() method of Child class"); } public void newMethod(){ System.out.println("new method of child class"); } public static void main( String args[]) { ABC obj = new ABC(); obj.disp(); ABC obj2 = new Demo(); // Covariance with reference types obj2.disp(); } } In the above example, we have defined the disp() method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter list of the methods are the same, and there is IS-A relationship between the classes.

Hierarchical Inheritance

class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ // Hierarchical Inheritance void bark(){System.out.println("barking...");} } class Cat extends Animal{ // Hierarchical Inheritance void meow(){System.out.println("meowing...");} } class TestInheritance3{ public static void main(String args[]){ Cat c=new Cat(); c.meow(); c.eat(); //c.bark(); //Error }}

Multilevel Inheritance

class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ //Level 1 - Inheritance void bark(){System.out.println("barking...");} } class BabyDog extends Dog{ //Level 2 - Inheritance void weep(){System.out.println("weeping...");} } class TestInheritance2{ public static void main(String args[]){ BabyDog d=new BabyDog(); d.weep(); d.bark(); d.eat(); }}

Single Inheritance

class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ //Single Inheritance void bark(){System.out.println("barking...");} } class TestInheritance{ public static void main(String args[]){ Dog d=new Dog(); d.bark(); d.eat(); }}

Access Modifiers with Method Overriding (Encapsulation)

class A{ *protected void msg(){System.out.println("Hello java");}* } public class Simple extends A{ *void msg(){System.out.println("Hello java");}* // Error because Class Simple method msg() is more restrictive than Class A method msg() public static void main(String args[]){ Simple obj=new Simple(); obj.msg(); } } If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.

Overloading the main() Method in Java (Polymorphism)

class TestOverloading4{ public static void main(String[] args){System.out.println("main with String[]");} public static void main(String args){System.out.println("main with String");} public static void main(){System.out.println("main without args");} } - Yes, by method overloading. You can have any number of main methods in a class by method overloading. But JVM calls main() method which receives string array as arguments only.

Method Overloading (Polymorphism)

if a class has multiple methods having the same name but different in parameters - If we have to perform only one operation, having same name of the methods increases the readability of the program *Changing the Number of Arguments* class Adder{ static int add(int a,int b){return a+b;} // 2 arguments static int add(int a,int b,int c){return a+b+c;} //3 arguments } class TestOverloading1{ public static void main(String[] args){ System.out.println(Adder.add(11,11)); System.out.println(Adder.add(11,11,11)); }} - In the above example, we have created two methods, first add() method performs *addition of two numbers* and second add method performs *addition of three numbers*. - In the above example, we are creating static methods so that we don't need to create instance for calling methods. *Changing Data Type of Arguments* class Adder{ static int add(int a, int b){return a+b;} // 2 arguments of int data type static double add(double a, double b){return a+b;} // 2 arguments of double data type } class TestOverloading2{ public static void main(String[] args){ System.out.println(Adder.add(11,11)); System.out.println(Adder.add(12.3,12.6)); }} - In the above example, we have created two methods that differs in data type. The first add method receives two *integer* arguments and second add method receives two *double* arguments.

Abstraction

is a process of hiding the implementation details and showing only functionality to the user - shows only essential things to the user and hides the internal details - for example, sending SMS where you type the text and send the message (you don't know the internal processing about the message delivery) - lets you focus on what the object does instead of how it does it

Polymorphism

is the ability of an object to take on many forms - occurs when there is a hierarchy of classes and they are related by inheritance - there are multiple children of a parent class - all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object

Generalization (Abstraction)

is the process of extracting shared characteristics from two or more classes, and combining them into a generalized superclass - shared characteristics can be attributes, associations, or methods - i.e. *Piece of Luggage* and *Piece of Cargo* partially share the same attributes to create a *new superclass Freight* - id, weight, and id number are those similar properties

Specialization (Abstraction)

means creating new subclasses from an existing class - if it turns out that certain attributes, associations, or methods only apply to some of the objects of the class, a subclass can be created - i.e. *Degree of Hazardousness* is a property within the subclass *Piece of Cargo* - also has all the properties of the superclass *Freight*


Conjuntos de estudio relacionados

Introduction to International Organizations

View Set

APUSH: Civil Rights Movement, Vietnam, Nixon

View Set

Chapter 13 Quiz: Albert Bandura: Modeling Theory

View Set

Chapter 17: Insurance and Billing pt.1

View Set

A & P SG #3- Joints/Articulations

View Set

Maternal and Newborn Medications

View Set

PEDs Chapt 30 Nursing Care of the Child with a Cognitive or Mental Health Disorder

View Set

Palliative Care - Oncology Pain Management

View Set