Oops
Oops
hashmap:
// Main class
public class GFG {
Here's a concise explanation of the four key OOP concepts along with their
advantages and disadvantages:
### 1. **Abstraction**
- **Explanation**: Abstraction involves hiding the complex implementation
details of a system and exposing only the necessary features. It allows you to
focus on what an object does rather than how it does it.
- **Advantages**:
- Simplifies code by focusing on essential features.
- Enhances code readability and maintainability.
- **Disadvantages**:
- May lead to less efficient code due to extra layers.
- Can be overused, leading to unclear or overcomplicated design.
### 2. **Encapsulation**
- **Explanation**: Encapsulation is the practice of bundling the data
(variables) and the methods (functions) that operate on the data into a single unit
or class. It restricts direct access to some of the object’s components, which is a
way of preventing accidental interference and misuse of the data.
- **Advantages**:
- Protects the integrity of the data by controlling access.
- Increases modularity and flexibility of the code.
- **Disadvantages**:
- Can make the code more complex.
- Requires careful design to avoid making the class too restrictive.
### 3. **Polymorphism**
- **Explanation**: Polymorphism allows objects of different classes to be
treated as objects of a common super class. The most common use is when a parent
class reference is used to refer to a child class object. It allows one interface
to be used for a general class of actions.
- **Advantages**:
- Facilitates code reusability and flexibility.
- Makes the code more scalable by allowing methods to work on different types.
- **Disadvantages**:
- Can make the code harder to understand and debug.
- If not properly managed, it may lead to runtime errors.
### 4. **Inheritance**
- **Explanation**: Inheritance allows a new class to inherit properties and
behavior (methods) from an existing class. The new class, known as a subclass, can
add its own functionality or override the inherited one.
- **Advantages**:
- Promotes code reuse by inheriting common functionality.
- Helps in creating a hierarchical classification.
- **Disadvantages**:
- Can lead to tightly coupled code, making it harder to change or extend.
- Misuse can lead to a fragile base class problem, where changes in the base
class affect all derived classes.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------
imp syntax:
Each time a new object is created(with the new keyword), the constructor will be
invoked.
objects are created to access instance variables or class variables from other
public classes.
local variables can only be accessed via functions(return keyword)
**class is a blueprint
for a class say class house we can use this blueprint of the class to build as many
house we want
these houses are called instances or objects
all these houses(objects or instances) have an address known as refrence
you can copy this refrence as many times u want but the house address remains the
same
in other words u can have multiple refrences to the same object
class house{
private string color;
public House(String color)
{
this.color=color;
}
public string getcolor()
{
return color;
}
public void setcolor(string color)
{
this.color=color;
}
}
//a class house with instance variable(field) color
"this" keyword is used to access current class members. it is used when we have a
parameter with the same name as the instance variable
int varname;
function(int varname)
{this.varname=varname; //here this.objectname will refer to the variable outside
the function this satement is written in. where as the normal varname refers to the
parameter}
if there is no parameter in a function then the keyword "this" is optional to use
**A parameter is a value that you can pass to a method in Java. Then the method can
use the parameter as though it were a local variable initialized with the value of
the variable passed to it by the calling method.
this()
it is a keyword to call the main constructor from another overloaded constructor in
the same class
it should be the first statement in the overloaded constructor
super()
super() must be first line in each constructor
if we dont add it, java compiler does it on its own
super used to call parent constructors
it is also used to access functions from parent class
eg. of this()
public Rectangle()
{
this(0,0); //first constructor calls 2nd constructor
}
public Rectangle(int width, int height)
{
this(0,0,width,height); //2nd constructor calls 3rd constructor
}
public Rectangle(int x, int width, int height)
{
this.x=x;
this.y=y;
this.width=width;
this.height=height; //3rd constructor initializes all variables
}
//this is called coonstructor chaining
eg. of super()
class Shape{
private int x;
private int y;
public Shape(int x, int y)
{
this.x=x;
this.y=y
}
}
class Rectangle extends Shape{
private int width;
private int height;
public Rectangle(int x, int y)
{
this(x,y,0,0); //first constructor calls 2nd constructor
}
public Rectangle(int x, int width, int height)
{
super(x,y); //calls parent constructor
this.width=width;
this.height=height; //this constructor initializes all variables
}
-----------------------------------------------------------------------------------
---------------
method overriding and static vs instance
overriding has same name and same parameters whereas overloading has same name but
different parameters
overloaded method can have different access modifiers unlike in overriding(lower
access modifiers not allowed)
An overloaded method may or may not have different return types
static methods
cant use this keyword
methods that doesnt use instance variables then it should be declared as a static
method
can access static methods directly
eg.
class calculator{
public static void printsum(int a, int b)
{
sopln()
}
}
class main
{
psvm()
{
calculator.printsum(5,10); //as in different class but both static
printhello(); //as in same class and both static
}
psv printhello()
{
sopln("hello");
}
}
instance methods-
to acces these you have to make object using new keyword first
can directly access instance methods and variables directly
can also accesss static methods and variables directly
eg.
class dog
{
somefunction{//instance function}
}
class main
{
psvm()
{
Dog rex=new Dog;
rex.somefunction(); //static methods cant access instance methods directly
}
static variables have the same value for all the objects
class Test{
public static int a = 5;
public int b = 10;
}
// here t1 and t2 will have a separate copy of b
// while they will have same copy of a.
Test t1 = new test();
Test t2 = new test();
Test.a = 1//some value But you can not access instance variable like this
System.out.println(t1.a);
System.out.println(t2.a);
t1.b = 15 // will not be reflected in t2.
System.out.println(t1.b); // this will print 15
System.out.println(t2.b); / this will still print 10;
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------
accessing functions:
to access static methods from another class(regardless of the function from which
you are calling): classname.functionname();
to access instance methods from another class(regardless of the function from which
you are calling): objectname.functionname();
to access static variable of same class from a static method(outside the function)-
variablename;
to access static variable of same class from an instance method(outside the
function)- variablename;
to access instance variable of same class from an instance method(outside any
function)- variablename;
to access instance variable of same class from a static method(variable outside any
function)- objectname.variablename;
-----------------------------------------------------------------------------------
---------------------------------------------------------------------------
*static variables are always outside the function as static variables can't be
created inside a function
*you can't use access modifiers like public or private for variables inside a
function. you also can't use static for variables inside a function(hence the above
statement)
*you cant access variables inside another function in any way. only way is to
access the function first and see if it returns the variable you want or not
*eg to to access instance variable of same class from a static method(variable
inside different function)- objectname.functionname() //you will have to call the
function and see if it returns that variable as there is no way to access a
variable created inside another function
*if the variable is inside the same function doesn't matter if the function is
static or not you can access it directly by just using it's variablename normally
-----------------------------------------------------------------------------------
-----------------
composition
public Car(){
class Engine {
}
-----------------------------------------------------------------------------------
encapsulation
encapsulation is basically declaring the variables as private so that the only way
to access them is through getters and setters or through other public functions
basically private variables and public fnctions. public functions me parameter to
be passed has different variable name than instance(private wala) variable
eg.
package com.timbuchalka;
/**
* Created by dev on 31/07/15.
*/
public class EnhancedPlayer {
private String name;
private int hitPoints = 100;
private String weapon;
this.weapon = weapon;
}
package com.timbuchalka;
package com.timbuchalka;
/**
* Created by dev on 27/09/15.
*/
public interface ITelephone {
void powerOn();
void dial(int phoneNumber);
void answer();
boolean callPhone(int phoneNumber);
boolean isRinging();
}
package com.timbuchalka;
/**
* Created by dev on 27/09/15.
*/
public class DeskPhone implements ITelephone {
@Override
public void dial(int phoneNumber) {
System.out.println("Now ringing " + phoneNumber + " on deskphone");
@Override
public void answer() {
if(isRinging) {
System.out.println("Answering the desk phone");
isRinging = false;
}
@Override
public boolean callPhone(int phoneNumber) {
if(phoneNumber == myNumber) {
isRinging = true;
System.out.println("Ring ring");
} else {
isRinging = false;
}
return isRinging;
}
@Override
public boolean isRinging() {
return isRinging;
}
}
package com.timbuchalka;
}
}
-----------------------------------------------------------------------------------
------------
example for polymorphism:
package com.timbuchalka;
class Car {
private boolean engine;
private int cylinders;
private String name;
private int wheels;
@Override
public String startEngine() {
return "Mitsubishi -> startEngine()";
}
@Override
public String accelerate() {
return "Mitsubishi -> accelerate()";
}
@Override
public String brake() {
return "Mitsubishi -> brake()";
}
}
class Holden extends Car {
@Override
public String startEngine() {
return getClass().getSimpleName() + " -> startEngine()";
}
@Override
public String accelerate() {
return getClass().getSimpleName() + " -> accelerate()";
}
@Override
public String brake() {
return getClass().getSimpleName() + " -> brake()";
}
}
@Override
public String startEngine() {
return "Ford -> startEngine()";
}
@Override
public String accelerate() {
return "Ford -> accelerate()";
}
@Override
public String brake() {
return "Ford -> brake()";
}
}
}
-----------------------------------------------------------------------------------
---------
inner classes
package com.timbuchalka;
import java.util.ArrayList;
/**
* Created by dev on 2/10/2015.
*/
public class Gearbox {
private ArrayList<Gear> gears;
private int maxGears;
private int currentGear = 0;
private boolean clutchIsIn;
this.gearNumber = gearNumber;
this.ratio = ratio;
}
package com.timbuchalka;
}
}
-----------------------------------------------------------------------------------
------
abstract
package com.timbuchalka;
/**
* Created by dev on 7/10/2015.
*/
public abstract class Animal {
private String name;
package com.timbuchalka;
/**
* Created by dev on 7/10/2015.
*/
public abstract class Bird extends Animal {
public Bird(String name) {
super(name);
}
@Override
public void eat() {
System.out.println(getName() + " is pecking");
}
@Override
public void breathe() {
System.out.println("Breathe in, breathe out, repeat");
package com.timbuchalka;
/**
* Created by dev on 7/10/2015.
*/
public class Dog extends Animal {
@Override
public void eat() {
System.out.println(getName() + " is eating");
}
@Override
public void breathe() {
System.out.println("Breathe in, breathe out, repeat");
}
}
package com.timbuchalka;
/**
* Created by dev on 7/10/2015.
*/
public class Parrot extends Bird {
@Override
public void fly() {
System.out.println("Flitting from branch to branch");
}
}
package com.timbuchalka;
/**
* Created by dev on 7/10/2015.
*/
public class Penguin extends Bird {
public Penguin(String name) {
super(name);
}
@Override
public void fly() {
System.out.println("I'm not very good at that, can I go for a swim
instead?");
}
}
package com.timbuchalka;
function(int x, int y)
{
if(y!=0)
return x/y;
else
return 0;
//idar u check if denominator is zero or not before performing the action
}
----------------------------------------
ask for forgiveness(afp):
try catch method-
function(int x, int y)
{
try
{return x/y;}
catch(ArithmeticException e)
{return 0;}
//idr u directly do the action and then check the condition
}
eg.
int n=getNumberfunc();
while(true) {
try {
return s.nextInt(); //imp remember this thing to throw ur own exceptions
}
catch(InputMismatchException e) {
s.nextLine(); //to prevent infinite loop
System.out.println("message to be displayed instead of exception message shown by
compiler");
}}}
//now compiler will catch whatever exception u have done in the function and
display the sout statement accordingly
-------------------------------------------
throwing exceptions:
u can catch say InputMisMatch exception and throw arithmeticException using this
and inputmismatch ke badle compiler will show arithemetic exception ka msg using
this trick:
eg.
int n=getNumberfunc();
while(true) {
try {
return s.nextInt(); //imp remember this thing to throw ur own exceptions
}
catch(InputMismatchException e) {
throw new ArithmeticException("whatever xyz")
//this will throw a completely new exception(arithmetic) instead of the correct one
shown by compiler(inputmismatch)
}}}
//now compiler will throw whatever exception u have done in the function and
display the output statement accordingly
--------------------------------------
catching multiple exceptions:
import package.*;
If you use package.* then all the classes
and interfaces of this package will be
accessible but not subpackages.
The import keyword is used to make the
classes and interface of another package
accessible to the current package.
import package.classname;
If you import package.classname then only
declared class of this package will be accessible.
eg.
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();
//using fully qualified name
obj.msg();
}
}
Output:Hello
subpackage:
eg. In this example, we created
a package LearnJava and
a sub package corejava in the Simple.java file.
package LearnJava.corejava;
class Simple{
public static void main(String args[]){
System.out.println("Hello from subpackage");
}
}
-----------------------------------------------------------------------------------
----------
constructors:
package com.timbuchalka;
/**
* Created by dev on 8/3/15.
*/
public class Account {
private String number;
private double balance;
private String customerName;
private String customerEmailAddress;
private String customerPhoneNumber;
public Account() {
this("56789", 2.50, "Default name", "Default address", "default
phone"); //"this" is used to pass on the values to another constructor
System.out.println("Empty constructor called");
}
//constructors are written without return type
//only access specifier (public private etc.) and class name
//they are used to initialize an object
//they are called while the object is being created
//without a constructor java creates a default constructor with default values in
it
//constructors are used to give values to the fields of a class(ie variables
outside the function
//constructor overloading can be done with different parameters being passed
//use 1 constructor instead of multiple setters
package com.timbuchalka;
bobsAccount.withdrawal(100.0);
bobsAccount.deposit(50.0);
bobsAccount.withdrawal(100.0);
bobsAccount.deposit(51.0);
bobsAccount.withdrawal(100.0);
Eg
Flight f1= new Flight("dhruv",100,3567.4);
Flight f2= new Flight(f1); //complete copy
Flight f3=f1; //this is not constructor calling only refrencing
-----------------------------------------------------------------------------------
---------------------------
inheritence
package com.timbuchalka;
/**
* Created by dev on 8/3/15.
*/
public class Animal {
}
//these functions can be accessed by the kid class by creating an object
}
-----------------------------------------------------------------------------------
---------------------------------------------------------
package com.timbuchalka;
/**
* Created by dev on 8/3/15.
*/
public class Dog extends Animal {
-----------------------------------------------------------------------------------
-------------------------------------
package com.timbuchalka;
}
}
Output-
Dog.eat() called
Dog.chew() called
Animal.eat() called
Agar overide wala function nai likha hota inside kid class to output-
"Animal.eat called"
*even inherited classes can't access variables from parent classes without creating
an object for parent class first
(public or private doesn’t matter)
*you cant access even public variables without creating an object in another class
*to access public variables from a public class create an object and use
objectname.variablename=xyz;
*to access private variables from a private class use public getters and setter. u
cant access them directly by using objectname.variablename.
*this is same in inherited classes and normal classes
*one extra way to access functions from kid class to parent class is using super()
function
*super(parameters) for constructors and super.functionname(parameters) for other
functions in parent class
*
public Dog(String name, brain, body int size, int weigh) {
super(name, brain, body, size, weight);
}
For this function lets say we know dog has 1 body and 1 brain always so we can just
define that pehle se
Eg
public Dog(String name, int size, int weight, int eyes, int legs, int tail, int
teeth, String coat) {
super(name, 1,1, size, weight);
}
Here we remove body and brain from kid class constructor and in the super function
we replace brain and body with its integers
-----------------------------------------------------------------------------------
------------------------------
Hashing
A hash collision occurs when two different keys map to the same index in a hash
table
Hashset vs Hashmap
A hashset does not contain duplicates. hashmap has unique keys but can have
duplicate values.
Hashset me sirf values hoti, map me key and value.
Hashset O(n) and HashMap O(1)[check]
HashMap vs Map
The Map is an interface, and HashMap is a class of the Java collection framework
that uses this map interface.
The Map does not allow null values. But the HashMap can have one null key and
multiple values.
--------------------------------------------------------------------------------
hashmap syntax: