Revature 1

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Terms used in Inheritance & syntax

-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.

Inheritance & Advantages

-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. -Inheritance represents the IS-A relationship which is also known as a parent-child relationship. Advantages of Inheritance: -For method overriding (so runtime polymorphism can be achieved) -for code reusability

Advantages of OOPs over POPs

-OOPs makes development and maintenance easier whereas in a procedure-oriented programming language it is not easy to manage 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. Sample class: public class Dog { String breed; int age; String color; void barking() { } void hungry() { } void sleeping() { } }

Abstract Class

A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated. Some points to remember : 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.

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. However, you can provide the same values also. 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. We can have any number of parameters in the constructor.

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 of Abstract Class with an Abstract Method abstract class Bike{ // Abstract class abstract void run(); // Abstract method } class Honda4 extends Bike{ void run(){System.out.println("running safely");} public static void main(String args[]){ Bike obj = new Honda4(); obj.run(); } } Exercise: To create an abstract class called Bank. To create an abstract method called getRateOfInterest(); To create two subclasses called SBI - 7% and PNB - 5% as two banks that extend the abstract class Bank. To implement different functionalities for the getRateOfInterest() method in the SBI and PNB classes through the concept of method overriding and print out the interest rate inside the main() method created separately in a test class called TestBank

Types of constructors:

-Default -Parameterized constructor

Read & Write only classes

//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 //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; } }

Abstraction (4th term lol)

Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it 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. Abstraction lets you focus on what the object does instead of how it does it. Ways to achieve abstraction? -Abstract class (0-100%) -Interface (100%)

Example of Inheritance

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. 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); } }

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 same as class name.

Generalization

Generalization 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. Eg : The classes Piece of Luggage and Piece of Cargo partially share the same attributes. From a domain perspective, the two classes are also very similar. During generalization, the shared characteristics are combined and used to create a new superclass Freight . Piece of Luggage and Piece of Cargo become subclasses of the class Freight. Therefore the properties that are common to the classes Piece of Luggage and Piece of Cargo are placed in the superclass Freight - Identification, Weight and ID-Number are those properties.

Method Overloading

If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. If we have to perform only one operation, having same name of the methods increases the readability of the program. Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs.

What is a Constructor

In Java, a constructor is a block of codes similar to the method. It is called when an instance of the object is created, and memory is allocated for the object. It is a special type of method which is used to initialize the object. INITIALIZES an object (method is like function?) (you can init parameters like height etc)

Method overloading vs overriding

Method Overloading : Method overloading is used to increase the readability of the program. Method overloading is performed within class. In case of method overloading, parameter must be different. Method overloading is the example of compile time polymorphism. In java, method overloading 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 : Method overriding is used to provide the specific implementation of the method that is already provided by its super class. Method overriding occurs in two classes that have IS-A (inheritance) relationship. In case of method overriding, parameter must be same. Method overriding is the example of run time polymorphism. Return type must be same or covariant in method overriding. Sample exercise!! Consider a scenario where Bank is a class that provides functionality to get the rate of interest. However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate of interest. Go ahead and code the above scenario.

Types of Inheritance in Java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later. -> = IS A 1) Single: ClassB->ClassA 2) Multilevel: ClassC->ClassB->ClassA 3) Hierarchical: ClassB,ClassC->ClassA 4) Multiple ClassC->ClassA,ClassB 5) Hybrid: ClassD->ClassB, ClassC->ClassA

Polymorphism

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. Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.

Inheritance Code

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(); }} 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(); }} 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 }}

Default Constructor

The default constructor is a no-args constructor that the Java compiler inserts on your behalf; it contains a default call to super(); which is the default behavior. If you implement any constructor then you no longer receive a default constructor. Note : If there is no constructor in the class, the compiler adds a default constructor No arg constructor: 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. Note : a default constructor is added by the compiler when there is no constructor declared in the class.

Access Modifiers

There are two types of modifiers in java: access modifiers and non-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 There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. Here, we will learn access modifiers. See table for full access

Creating a constructor rules:

There are three rules defined for the constructor. -Constructor name must be the same as its class name -A Constructor must have no explicit return type -A Java constructor cannot be abstract, static, final, and synchronized

Why no multiple inheritance Java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java. 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. Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error. 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? } }

When is a constructor called?

When an object is created, compiler makes sure that constructors for all of its subobjects (its member and inherited objects) are called. If members have default constructors or constructor without parameter then these constructors are called automatically, otherwise parameterized constructors can be called using initializer list. Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.

Access modifier with method overriding

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 that 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. See sample exercise??? Lmao fck you Create an encapsulated class with 4 fields and the respective methods to access and edit those fields. Then go ahead and create a test class to verify. Class Name : Student Field Names : studentId, studentName, collegeName, address Test Class Name : TestStudent

Overloading methods

Change # 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. Change data type: 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. Note : Method overloading is not possible by changing the return type of the method.

Encapsulation

Encapsulation in Java is a process of 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. Now we can use setter and getter methods to set and get the data in it. The Java Bean class is the example of a fully encapsulated class. Advantages of encapsulation: By providing only a setter or getter method, you can make the class read-only or write-only. In other words, you can skip the getter or setter methods. It provides you the control over the data. Suppose you want to set the value of id which should be greater than 100 only, you can write the logic inside the setter method. You can write the logic not to store the negative numbers in the setter methods. It is a way to achieve data hiding in Java because other class will not be able to access the data through the private data members. The encapsulate class is easy to test. So, it is 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()); } }

Method Overriding (def, usage&rules, example)

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. Usage and Rules for Method Overriding Usage : 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 : 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). Example for Method Overriding 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(); } } Can static method be overridden? NO! It can be proved by runtime polymorphism, so we will learn it later. It is because the static method is bound with class whereas instance method is bound with an object. Static belongs to the class area, and an instance belongs to the heap area.

Constructor Overloading

In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods. Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types. 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(); } }

4 OOP Pillars

Inheritance Polymorphism Encapsulation Abstraction

Classes and Objects

Object: Any entity that has state and behavior is known as an object. For example a chair, pen, table, keyboard, bike, etc. It can be physical or logical. An Object can be defined as an instance of a 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. 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 like color, name, breed, etc. as well as behaviors like wagging the tail, barking, eating, etc. Class: A class, in the context of Java, are 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 class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume any space.

Specialization

Specialization 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. In the previous example for Generalization, we saw that the classes Piece of Luggage and Piece of Cargo shared similar properties that were placed in a superclass called Freight. When it comes to Specialization, if there is a property that is only applicable to a specific subclass, such as Degree of Hazardousness, that property is placed in the class Piece of Cargo where-in this class also has all the properties of the Freight class with the concept of Generalization.

Overloading the main() method in Java

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.


Kaugnay na mga set ng pag-aaral

Chapter 12 & 13 - Waves and Sounds

View Set

bcis review 6, bcis lesson 10, bcis 7 review, bcis lets review 9

View Set

Progression: Field Tech III - IV Conventional

View Set

US History B - Era of Cultural Change (Unit #4)

View Set

AP World History Period 4: Global Interactions (c. 1450 to c. 1750)

View Set

Understanding Numbers in Development

View Set

CHAPTER 11: Rhyming Singers of the Bahamas, "My Lord Help Me to Pray"

View Set