[go: up one dir, main page]

0% found this document useful (0 votes)
34 views25 pages

Oops

oops interview prep

Uploaded by

Dhruv Sompura
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views25 pages

Oops

oops interview prep

Uploaded by

Dhruv Sompura
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 25

oops

hashmap:

// Java Program to illustrate the Hashmap Class

// Importing required classes


import java.util.*;

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating an empty HashMap


Map<String, Integer> map = new HashMap<>();

// Inserting entries in the Map


// using put() method
map.put("vishal", 10);
map.put("sachin", 30);
map.put("vaibhav", 20);

// Iterating over Map


for (Map.Entry<String, Integer> e : map.entrySet())

// Printing key-value pairs


System.out.println(e.getKey() + " "
+ e.getValue());
}
}
-------------------------------------------------------------------------
//check if element has appeared once
map.get(nums[i]) == 1
-------------------------------------------------------------------
virtual function: overridden functions

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:

while taking string input in between int and float etc


eg.
Scanner sc=new Scanner();
int b= sc.nextInt();
sc.nextLine(); //do this before taking string input
String names=sc.nextLine();
float price=sc.nextfloat();

2d array syntax: int[][] twoD_arr = new int[10][20];


num to string to array: char[] s = Integer.toString(num).toCharArray();
array to string to num: Integer.parseInt(s.toString())
char to int: int a = Integer.parseInt(String.valueOf(ch));
int to char: char c=(char)a;
replace a character in string: str = str.substring(0, index) + ch +
str.substring(index + 1);
Math.abs, Math.min
sort: Arrays.sort(nums);
binary represenation of integer: String binary=Integer.toBinaryString(i);
a^b=c then a^c=b
absolute values: Math.abs(x);
append: StringBuilder missingChars = new StringBuilder(); missingChars.append(c);
-----------------------------------------------------------------------------------
---------------------------------------------
refrences, objects and instances
A class can contain any of the following variable types.
Local variables − Variables defined inside methods, constructors or blocks are
called local variables. The variable will be declared and initialized within the
method and the variable will be destroyed when the method has completed.
Instance variables − Instance variables are variables within a class but outside
any method. These variables are initialized when the class is instantiated.
Instance variables can be accessed from inside any method, constructor or blocks of
that particular class.
Class variables − Class variables are variables declared within a class, outside
any method, with the static keyword.

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

public class main()


{
psvm()
{
//this class will create instances of class house
House bluehouse=new House("blue"); //this line creates a new instance for the house
class and sets color to blue
//bluehouse is a refrence that points to the object of type House in memory
House anotherhouse=bluehouse; //both refrences point to the same object in memory
now
//we have 2 refrences for 1 object
sopln(getcolor(anotherhouse)); //blue //as both bluehouse and another house point
to the same object so they share the same characteristics
sopln(getcolor(bluehouse)); //blue
anotherhouse.setcolor("yellow"); //calls the method setcolor and sets the color to
yelow
sopln(getcolor(anotherhouse)); //yellow
sopln(getcolor(bluehouse)); //yellow
House greenhouse=new House("green"); //creates a new instance to the house class
with color green
anotherhouse=greenhouse; //anotherhouse and greenhouse becomes green and bluehouse
is yellow
//we have 3 refrences for 2 objects
}}
-----------------------------------------------------------------------------------
-------------------------------------------------
this vs super the keyword battle

super keyword is used to access parent class members(variables and functions)

"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

a constructor cant have both super() and this()

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

overridden method must have same name and same arguments


now lower access modifier ie if parent method has protected as modifier then kid
method cant have private but can have public
constructors and private methods cant be overriden

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

static method calling-


if in different classes use classname.methodname()
if in same class use methodname()
no need to make instance

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
}

instance variable vs staic variable


Instance variables can be accessed directly by calling the variable name inside the
class. However, within static methods (when instance variables are given
accessibility),
they should be called using the fully qualified name. ObjectReference.VariableName.

Static variables can be accessed by calling with the class name


ClassName.VariableName.

public class VariableExample{


int myVariable;
static int data = 30;

public static void main(String args[]){


VariableExample obj = new VariableExample();

System.out.println("Value of instance variable: "+obj.myVariable);


//objname.variablename
System.out.println("Value of static variable: "+VariableExample.data);
//classname.variablename
}
}

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 call static method from another static method(same class)- functionname();


to call static method from another instance method(same class)- functionname();
to call instance method from another instance method(same class)- functionname();

to call instance method from a static method(same class)-


objectname.functionname();
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------
accessing variables:

to access static variable of another class(regardless of the function from which


you are calling)- classname.variablename;
to access instance variable of another class(regardless of the function from which
you are calling)- objectname.variablename;

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

A composition in Java between two objects associated with each other


exists when there is a strong relationship between one class and another.
Other classes cannot exist without the owner or parent class.
For example, A ‘Human’ class is a composition of Heart and lungs.
When the human object dies, no body parts exist.

The composition is a restricted form of Aggregation.


In Composition, one class includes another class
and is dependent on it so that it cannot functionally exist without another class.

Implementation of Composition in Java


The engine and car relationship are implemented using Java classes as below.
In Java, the ‘final’ keyword is used to represent Composition.
This is because the ‘Owner’ object expects a part object to be available and
function by making it ‘final’.

public class Car {

private final Engine theengine;

public Car(){

theengine = new Engine();

class Engine {

private String type;

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

public EnhancedPlayer(String name, int health, String weapon) {


this.name = name;
if(health >0 && health <= 100) {
this.hitPoints = health;
}

this.weapon = weapon;
}

public void loseHealth(int damage) {


this.hitPoints = this.hitPoints - damage;
if(this.hitPoints <=0) {
System.out.println("Player knocked out");
// Reduce number of lives remaining for the player
}
}

public int getHealth() {


return hitPoints;
}
}

package com.timbuchalka;

public class Main {


EnhancedPlayer player = new EnhancedPlayer("Tim", 200, "Sword");
player.loseHealth(10);
System.out.println("Initial health is " + player.getHealth());
}
}
-----------------------------------------------------------------------------------
----------------
interfaces

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 {

private int myNumber;


private boolean isRinging;

public DeskPhone(int myNumber) {


this.myNumber = myNumber;
}
@Override
public void powerOn() {
System.out.println("No action taken, desk phone does not have a power
button");

@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;

public class Main {

public static void main(String[] args) {


ITelephone timsPhone; //can also use deskphone timphone instead
//but above cmnt will only work for timphone=new DeskPhone() and wont work
if any other class also implements the same interface
timsPhone = new DeskPhone(123456);
timsPhone.powerOn();
timsPhone.callPhone(123456);
timsPhone.answer();

}
}
-----------------------------------------------------------------------------------
------------
example for polymorphism:
package com.timbuchalka;

class Car {
private boolean engine;
private int cylinders;
private String name;
private int wheels;

public Car(int cylinders, String name) {


this.cylinders = cylinders;
this.name = name;
this.wheels = 4;
this.engine = true;
}

public int getCylinders() {


return cylinders;
}

public String getName() {


return name;
}

public String startEngine() {


return "Car -> startEngine()";
}

public String accelerate() {


return "Car -> accelerate()";
}

public String brake() {


return "Car -> brake()";
}
}

class Mitsubishi extends Car {

public Mitsubishi(int cylinders, String name) {


super(cylinders, name);
}

@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 {

public Holden(int cylinders, String name) {


super(cylinders, name);
}

@Override
public String startEngine() {
return getClass().getSimpleName() + " -> startEngine()";
}

@Override
public String accelerate() {
return getClass().getSimpleName() + " -> accelerate()";
}

@Override
public String brake() {
return getClass().getSimpleName() + " -> brake()";
}
}

class Ford extends Car {

public Ford(int cylinders, String name) {


super(cylinders, name);
}

@Override
public String startEngine() {
return "Ford -> startEngine()";
}

@Override
public String accelerate() {
return "Ford -> accelerate()";
}

@Override
public String brake() {
return "Ford -> brake()";
}
}

public class Main {

public static void main(String[] args) {


// We are going to go back to the car analogy.
// Create a base class called Car
// It should have a few fields that would be appropriate for a generice car
calss.
// engine, cylinders, wheels, etc.
// Constructor should initialize cylinders (number of) and name, and set
wheels to 4
// and engine to true. Cylinders and names would be passed parameters.
//
// Create appropriate getters
//
// Create some methods like startEngine, accelerate, and brake
//
// show a message for each in the base class
// Now create 3 sub classes for your favorite vehicles.
// Override the appropriate methods to demonstrate polymorphism in use.
// put all classes in the one java file (this one).

Car car = new Car(8, "Base car");


System.out.println(car.startEngine());
System.out.println(car.accelerate());
System.out.println(car.brake());

Mitsubishi mitsubishi = new Mitsubishi(6, "Outlander VRX 4WD");


System.out.println(mitsubishi.startEngine());
System.out.println(mitsubishi.accelerate());
System.out.println(mitsubishi.brake());

Ford ford = new Ford(6, "Ford Falcon");


System.out.println(ford.startEngine());
System.out.println(ford.accelerate());
System.out.println(ford.brake());

Holden holden = new Holden(6, "Holden Commodore");


System.out.println(holden.startEngine());
System.out.println(holden.accelerate());
System.out.println(holden.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;

public Gearbox(int maxGears) {


this.maxGears = maxGears;
this.gears = new ArrayList<>();
Gear neutral = new Gear(0, 0.0);
this.gears.add(neutral);
}

public void operateClutch(boolean in) {


this.clutchIsIn = in;
}

public void addGear(int number, double ratio) {


if((number >0) && (number <= maxGears)) {
this.gears.add(new Gear(number, ratio));
}
}

public void changeGear(int newGear) {


if((newGear>=0 ) && (newGear <this.gears.size()) && this.clutchIsIn) {
this.currentGear = newGear;
System.out.println("Gear " + newGear + " selected.");
} else {
System.out.println("Grind!");
this.currentGear = 0;
}
}

public double wheelSpeed(int revs) {


if(clutchIsIn) {
System.out.println("Scream!!!");
return 0.0;
}
return revs * gears.get(currentGear).getRatio();
}

private class Gear {


private int gearNumber;
private double ratio;

public Gear(int gearNumber, double ratio) {

this.gearNumber = gearNumber;
this.ratio = ratio;
}

public double getRatio() {


return ratio;
}

public double driveSpeed(int revs) {


return revs *( this.ratio);
}
}
}

package com.timbuchalka;

public class Main {

public static void main(String[] args) {


Gearbox mcLaren = new Gearbox(6);
Gearbox.Gear first = mcLaren.new Gear(1, 12.3);
// Gearbox.Gear second = new Gearbox.Gear(2, 15.4);
// Gearbox.Gear third = new mcLaren.Gear(3, 17.8);
System.out.println(first.driveSpeed(1000));

}
}
-----------------------------------------------------------------------------------
------
abstract
package com.timbuchalka;

/**
* Created by dev on 7/10/2015.
*/
public abstract class Animal {
private String name;

public Animal(String name) {


this.name = name;
}

public abstract void eat();


public abstract void breathe();

public String getName() {


return 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");

public abstract void fly();


}

package com.timbuchalka;

/**
* Created by dev on 7/10/2015.
*/
public class Dog extends Animal {

public Dog(String name) {


super(name);
}

@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 {

public Parrot(String name) {


super(name);
}

@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;

public class Main {

public static void main(String[] args) {


Dog dog = new Dog("Yorkie");
dog.breathe();
dog.eat();

Parrot parrot = new Parrot("Australian ringneck");


parrot.breathe();
parrot.eat();
parrot.fly();

Penguin penguin = new Penguin("Emperor");


penguin.fly();
}
}
---------------------------------------------------------------------------------
Exceptions:

look before you leap(lbyl):


normal method-

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
}

if input is x=100 y=0


function will check if arithmetic exception is there or not.
if it is preseent then output will be 0(because of return 0 in catch statement)
if arithematic exception not there then it will return x/y(try statement)
--------------------------------------------------------------
exception jujutsu part 1

(continuing a program even after an exception is caught)

now it is important to make new/different functions and call them instead of


directly writing the try catch in same function(jaha pe input lia)
as creating a new function gives u liberty to control your own exceptions
normally compiler will throw an exception all by itself

eg. int n=s.nextInt();


//regardless of what you type after this compiler will throw an exception by itself
//blah blah blah code compiler doesn't care

eg.

int n=getNumberfunc();

private static int getNumberfunc() {


Scanner s = new Scanner(System.in);
System.out.println("Please enter an integer ");

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:

public static void validate(int age) {


if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");}
else {
System.out.println("Person is eligible to vote!!");
}}

if input is less than 18 output will be:


Exception in thread "main" java.lang.ArithmeticException: Person is not eligible to
vote
--------------------------------------------
exception jujutsu part 2:

(throwing exceptions of your choice)

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

private static int getNumberfunc() {

Scanner s = new Scanner(System.in);System.out.println("Please enter an integer ");

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:

catch(ArithmeticException | NoSuchElementException e){}


--------------------------------------------------------------------------
There are three ways to access the package from outside the package.

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.

fully qualified name.


If you use fully qualified name then only declared class of this package will be
accessible.
Now there is no need to import. But you need to use fully qualified name every time
when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.

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

public Account(String number, double balance, String customerName, String


customerEmailAddress,
String customerPhoneNumber) {
System.out.println("Account constructor with parameters called");
this.number = number;
this.balance = balance;
this.customerName = customerName;
this.customerEmailAddress = customerEmailAddress;
this.customerPhoneNumber = customerPhoneNumber;
}

public void deposit(double depositAmount) {


this.balance += depositAmount;
System.out.println("Deposit of " + depositAmount + " made. New balance is "
+ this.balance);
}

public void withdrawal(double withdrawalAmount) {


if(this.balance - withdrawalAmount >= 0) {
System.out.println("Only " + this.balance + " available. Withdrawal not
processed");
} else {
this.balance -= withdrawalAmount;
System.out.println("Withdrawal of " + withdrawalAmount + " processed,
Remaining balance = " + this.balance);
}
}

public String getNumber() {


return number;
}

public double getBalance() {


return balance;
}
public String getCustomerName() {
return customerName;
}

public String getCustomerEmailAddress() {


return customerEmailAddress;
}

public String getCustomerPhoneNumber() {


return customerPhoneNumber;
}

package com.timbuchalka;

public class Main {

public static void main(String[] args) {


// Create a new class for a bank account
// Create fields for the account number, balance, customer name, email and
phone number.
//
// Create getters and setters for each field
// Create two additional methods
// 1. To allow the customer to deposit funds (this should increment the
balance field).
// 2. To allow the customer to withdraw funds. This should deduct from the
balance field,
// but not allow the withdrawal to complete if their are insufficient
funds.
// You will want to create various code in the Main class (the one created
by IntelliJ) to
// confirm your code is working.
// Add some System.out.println's in the two methods above as well.

Account bobsAccount = new Account(); // "12345", 0.00, "Bob Brown",


"myemail@bob.com",
// "(087) 123-4567");
//the first constructor gets initialized over here and the values given in the 1st
constructor are passed
System.out.println(bobsAccount.getNumber());
System.out.println(bobsAccount.getBalance());

bobsAccount.withdrawal(100.0);

bobsAccount.deposit(50.0);
bobsAccount.withdrawal(100.0);

bobsAccount.deposit(51.0);
bobsAccount.withdrawal(100.0);

//no need for setters now


}
}
Copy constructors:
Copying a constructor onto another constructor
Either completely or only some data

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 {

private String name;


private int brain;
private int body;
private int size;
private int weight; //variables that can be common with kid class

//constructor for parent class(compulsory)


public Animal(String name, int brain, int body, int size, int weight) {
this.name = name;
this.brain = brain;
this.body = body;
this.size = size;
this.weight = weight;
}
//the below method is called when animal.eat() is used
//if the method is not overriden in the kid class then this method is called when
dog.eat() is used
public void eat() {
System.out.println("Animal.eat() called");
}

public void move(int speed) {


System.out.println("Animal.move() called. Animal is moving at " +speed);

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

//extends used to create kid class

private int eyes;


private int legs;
private int tail;
private int teeth;
private String coat;
//new variables for kid class

//u need a constructor for kid class to do inheritance


public Dog(String name, brain, body int size, int weight, int eyes, int legs,
int tail, int teeth, String coat) {
super(name, brain, body, size, weight); //super is used to call constructor of
parent class(animal) so has all the variables common in both the classes
this.eyes = eyes;
this.legs = legs;
this.tail = tail;
this.teeth = teeth;
this.coat = coat;
//these variables are only in dog class
}
private void chew() {
System.out.println("Dog.chew() called");
}

//the below method is called when dog.eat() is used as it is overriden


//overide functions are not compulsory
@Override
public void eat() {
System.out.println("Dog.eat() called"); //prints this when dog.eat() called
chew(); //calls chew
super.eat(); //calls eat() function from parent class(also compulsory)
}
//if override wala function was not written then dog.eat() pe seedha parent class
wala function gets executed Ie output is "animal.eat() called" only

public void walk() {


System.out.println("Dog.walk() called");
super.move(5); //directly parent class ka move is called
}

public void run() {


System.out.println("Dog.run() called");
move(10); //move of this class is called that is overriden move
//agar overridden function nai likha hota to parent class ka move call hota seedha

private void moveLegs(int speed) {


System.out.println("Dog.moveLegs() called");
}
@Override
public void move(int speed) {
System.out.println("Dog.move() called");
moveLegs(speed);
super.move(speed);
}
}

-----------------------------------------------------------------------------------
-------------------------------------
package com.timbuchalka;

public class Main {

public static void main(String[] args) {


Animal animal = new Animal("Animal", 1, 1, 5, 5);

Dog dog = new Dog("Yorkie", 8, 20, 2, 4, 1, 20, "long silky");


dog.eat(); //if override nahi hota to animal wala eat function call hota
seedha
//dog.walk(); //comment kia taaki output me confuse na hoe
//dog.run():
//dog.walk pe "animal.move is called" print hoga
//dog.run pe "dog.move is called, "dog.movelegs is called and animal.move is
called" sab print hoga

}
}
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:

int nums[]={blah blah};


HashMap<Integer, Integer> hmap = new HashMap<>();
int count = 0;
for (int num : nums) {
if (hmap.containsKey(num)) {
count += hmap.get(num);
hmap.put(num, hmap.get(num) + 1);
} else {
hmap.put(num, 1);
}
}
return count;
}

to loop through strings:


String s="abc"
String[] substrings2 = s.split("");

for (String c : substrings) {


hmap.put(c,i);
i++;
}
----------------------------------------------------------------------------------

You might also like