Skip to content

Repository files navigation

Java Notes:

Classes & Objects:

  • OOP: Object Oriented Programming: Style of Writing Code.
  • Objects: Entities in Real World.
  • Casses: Group of these Entities | Collection of Real World Objects | BluePrint of on object | has Attributes & Methods | ex: Pen
  • Attributes: Properties | ex: color, thickness
  • Methods: Functions Which is use in the Class | Behaviours | ex: setColor(), setTip()
  • Java Code Writing Convention: Traditional Java Developers Follow this Convention
    • Always Make Classes After Public Class.
    • File_Name & Public_Class_Name Should be Same.
    • Class name Should be Start With Capital Letter.
    • Methords name Should be Start with Small Letter - CamelCase.

Code:

publicclassOOP{
// Compiler Always Start Execution From Main Method:// Public: Access Specifier.// Static: Without Creating Object to Use Main Method. // Void: Return DataType.publicstaticvoidmain(Stringargs[]){ // Pen: Class.// P1: Reference Variable.// new: Memory Allocation.// Pen(): Pen Class Default Constructor.// ; : Treminate the Line.// Created a Pen Object called p1.// Stack:// Heap: Object Created in Heap Memory (alocates Memory) by using New Keyword. Penp1 = newPen(); p1.setColor("BLue");
// p1.color = "Green"; We can Also Write in this Way. System.out.println(p1.color);
p1.setTip(10);
System.out.println(p1.tip);
}
}
// Pen ClassclassPen{
// Properties and Methods:Stringcolor = "Red";
inttip = 5;
voidsetColor(StringnewColor){
color = newColor;
}
voidsetTip(intnewTip){
tip = newTip;
}
}
// Student ClassclassStudent{
Stringname;
intage;
floatpercentage;
voidcalcPercentage(intphy, intche, intmath){
percentage = (phy + che + math)/3;
}
}

Access Modifiers:

Access SpecifierWithin ClassWithin PackageOutside Package BySubClass OnlyOutSide Package
- Private:YNONONO
- Default:YYNONO
- Protected:YYYNO
- Public:YYYY

Getter & Setter:

  • Get: To Return the Value.
  • Set: To Modify the Value.
  • This Keyword is Used to refer to the Current Object.
publicclassOOP{
publicstaticvoidmain(Stringargs[]) {
Penp1 = newPen();
p1.setColor("Red");
p1.setTip(10);
System.out.println(p1.getColor());
System.out.println(p1.getTip());
}
}
classPen {
privateStringcolor;
privateinttip;
StringgetColor(){
returnthis.color;
}
intgetTip(){
returnthis.tip;
}
voidsetColor(StringnewColor){
// you can use this when instance variable and local variable names are same // color: Instance Variable.// newColor: Local Variable. this.color = newColor;
}
voidsetTip(intnewTip){
this.tip = newTip;
}
}

Encapsulation:

  • Four Pillers of OOP.
    • Encpsulation: Encapsulation is defined as the wrapper up of Data & Methods ( Properties|Variables & Functions) under a Single Unit. It also Implements Data Hiding (Useless | Sensitive -> Private|Protected|Default ).
    • Abstraction:
    • Inheritance:
    • Polimorphisum:

Constructors:

  • Constructor is a Special Method which is invoked by Automatically at the time of Object Creation.
    • Constructor have the Same name as Class Structure.
    • Constructor Don't have Return Type.(Not even void)
    • Constructors are Only called Once.
    • Memory Allocation happens when Constructor is Called.
  • Types Of Constructor:
    • Non-Parametrized:
    • Parametrized:
      • Constructor Overloading - Polymorphisum
    • Copy Constructor:
      • Shallw (On a Surface Changes) Copy: Refrence Copy - Changes Reflect
      • Deep (Totally Deep Inside Changes) Copy: New Copy - Changes Not Reflect
publicclassOOP{
publicstaticvoidmain(Stringargs[]) {
Students1 = newStudent();
Students2 = newStudent("Pratik",22,"12345");
s2.marks[0] = 90;
s2.marks[1] = 95;
s2.marks[2] = 99;
// Copy Constructor:Students3 = newStudent(s2);
// Beacouse of Array are Referece Variables.s3.password = "67890";
s2.marks[2] = 12; for(inti=0; i<3;i++){
System.out.println(s3.marks[i]);
}
}
}
classStudent{
Stringname;
introllno;
Stringpassword;
intmarks[];
// Default Constructor | Non-Parametrized Constructor:Student(){
System.out.println("Student Constructor Called...");
}
// Parametrized Constructor:Student(Stringname, introllno, Stringpassword){
this.name = name; this.rollno = rollno;
this.password = password;
marks = newint[3];
}
// Copy Constructor: Shallw Copy Constructor// Student(Student s2){// this.name = s2.name;// this.rollno = s2.rollno;// this.marks = s2.marks;// }// Deep Copy Constructor:Student(Students2){
marks = newint[3];
this.name = s2.name;
this.rollno = s2.rollno;
this.marks = s2.marks;
for(inti =0; i<3; i++){
this.marks[i] = s2.marks[i];
}
}
}

Destructors:

  • Garbage Collector:

Inheritance:

  • Inheritance is when Properties and Methods of base | Parent | Super class are passed on Derived | Child | Sub Class.
  • In Java Multiple Inheritance is Not Exist | Not Possible by Classes. But We Can Achive by using Interface.
  • Multiple Base Class - Single Derived Class

Single Level Inheritance:

  • Single Base Class to Single Child Class (1 on 1):
  • Single Level Inheritance
// Inheritance// Singlr Level InheritancepublicclassOOP{
publicstaticvoidmain(String[] args) {
Fishshark = newFish();
shark.eat(); }
}
// BaseCLassclassAnimal{
Stringcolor;
voideat(){
System.out.println("Eats");
}
voidbreath(){
System.out.println("Breathes");
}
}
// DerivedClassclassFishextendsAnimal{
intfins;
voidswim(){
System.out.println("Swims in Water");
}
}

Multiple Inheritance:

  • Single Base class to Single Child Class Again Inherit by Another Single Child Classes (1 on 1 on 1...):
  • Single Level Inheritance
```javapublicclassOOP{
publicstaticvoidmain(String[] args) {
Dogdobby = newDog();
dobby.eat();
dobby.legs = 4;
System.out.println(dobby.legs);
}
}
classAnimal{
Stringcolor;
voideat(){
System.out.println("Eats");
}
voidbreathe(){
System.out.println("Breaths");
}
}
classMammalextendsAnimal{
intlegs;
}
classDogextendsMammal{
Stringbreed;
}

Hierarchial Inheritance:

  • Single Base class to Many Child Class (1 on MANY):
  • Single Level Inheritance
publicclassOOP{
publicstaticvoidmain(String[] args) {
Mammal
}
}
classAnimal{
Stringcolor;
voideat(){
System.out.println("Eats");
}
voidBreath(){
System.out.println("Breathes");
}
}
classMammalextendsAnimal{
voidwalk(){
System.out.println("Walks");
}
}
classFishextendsAnimal{
voidswim(){
System.out.println("Swims");
}
}
classBirdextendsAnimal{
voidfly(){
System.out.println("Fly");
}
}

Hybrid Inheritance:

  • Single Base class to Many Child Class Again Inherit by Another Many Child Classes (1 on MANY on Many) Combination of all inheritance:
  • Single Level Inheritance
// Hybrid Inheritance:publicclassOOP{
publicstaticvoidmain(String[] args) {
Dogdobby = newDog();
dobby.eat();
dobby.breath();
dobby.walk();
dobby.bark();
}
}
classAnimal{
Stringcolor;
voideat(){
System.out.println("Eats");
}
voidbreath(){
System.out.println("Breathes");
}
}
classMammalextendsAnimal{
voidwalk(){
System.out.println("Walks");
}
}
classFishextendsAnimal{
voidswim(){
System.out.println("Swims");
}
}
classBirdextendsAnimal{
voidfly(){
System.out.println("Fly");
}
}
classDogextendsMammal{
voidbark(){
System.out.println("Barking");
}
}

Polymorphism:

  • Poly: Many
  • Morph: Forms
  • Compile Time Polymorphism (Static)
    • Methord Overloading: Multiple Functions with the Same Name but Different Parameters.
  • Run Time Polymorphism (Dynamic)
    • Method Overriding: Parent and Child Classes both Contain the Same functions with a Different Defination.

Method Overloading:

  • Multiple Functions with the Same Name but Different Parameters.
// Polymorphism:// Compile Time Polymorphism:// Method Overloading:publicclassOOP{
publicstaticvoidmain(String[] args) {
Calculatorcalc = newCalculator();
System.out.println(calc.sum(2,3));
// System.out.println(calc.sum(2.2,3.3)); By Default it takes as a Double thts why we have to Type Cast.System.out.println(calc.sum((float)2.2,(float)3.3));
System.out.println(calc.sum(2,3,4));
}
} classCalculator{
intsum(intnum1, intnum2){
returnnum1+num2;
}
floatsum(floatnum1, floatnum2){
returnnum1+ num2;
}
intsum(intnum1, intnum2, intnum3){
returnnum1+num2+num3;
}
}

Method Overloading:

  • Parent and Child Classes both Contain the Same functions with a Different Defination.
// Polymorphism:// Run Time Polymorphism:// Method Overriding:publicclassOOP{
publicstaticvoidmain(String[] args) {
Deerdeer = newDeer();
deer.eat();
Animalanimal = newAnimal();
animal.eat();
}
} classAnimal{
voideat(){
System.out.println("Eats");
}
}
classDeerextendsAnimal{
voideat(){
System.out.println("Eats Grass");
}
}

Packages:

  • Packages is a Groupof Similar Types of Classes, Interfaces and Sub-Packages.
  • InBuild Packages: java.util.*;
  • UserDefined Packages: package myPackage;

Abstraction:

  • Hiding all the Unnecessary details and showing only the important parts to the user. Idea & Implimentation
  • Abstract Classes
  • Interfaces
  • Connot create create an instance | Object of Abstract Class.
  • Can have Abstract/Non-Abstract Class.
  • Can have Constructor.
// Abstract:publicclassOOP{
publicstaticvoidmain(Stringargs[]){
Horsehourse = newHorse();
hourse.eat();
hourse.walk();
Peacockpeacock = newPeacock();
peacock.eat();
peacock.walk();
MustangmyHorse = newMustang();
// Animal - Horse - Mustang. 
}
}
abstractclassAnimal{
Stringcolor;
Animal(){
color= "White";
System.out.println("Animal Constructor Called.");
}
voideat(){
System.out.println("Animal Eats");
}
abstractvoidwalk(); //Gives Idea and You have to be this Methoed when you extends. 
}
classHorseextendsAnimal{
voidchangColor(){
color = "Black";
}
Horse(){
System.out.println("Hourse Constructor Called.");
}
voidwalk(){
System.out.println("Hourse walks on 4 legs.");
}
}
classMustangextendsHorse{
Mustang(){
System.out.println("Mustang Constructor Called.");
}
}
classPeacockextendsAnimal{
voidchangColor(){
color = "Purple";
}
voidwalk(){
System.out.println("Peacock walks on 2 legs.");
}
}
// Animal Constructor Called.// Hourse Constructor Called.// Animal Eats// Hourse walks on 4 legs.// Animal Constructor Called.// Animal Eats// Peacock walks on 2 legs.// Animal Constructor Called.// Hourse Constructor Called.// Mustang Constructor Called.

Interface:

  • Interface is Blueprint of a class.
  • Interface(Blueprint of Class) - Class(Blueprint of Object) - Object
  • Use Interface Keyword
  • All Methods are Public, Abstract & Without Imlimentation.
  • Used to achieve total Abstraction.
  • Varible in the Interface are Finaly, Public and Static.
  • Class - Extends
  • Interface - Impliment
  • Total Abstraction (Interfaces)
  • Multiple Inheritance (Implimentation)
  • Single Level Inheritance
// Interface: Blueprint of Class: Achive Multiple Inheritance:publicclassOOP{
publicstaticvoidmain(Stringargs[]) {
Queenqueen = newQueen();
queen.moves();
}
}
interfaceChessPlayer{
voidmoves();
}
classQueenimplementsChessPlayer{
publicvoidmoves(){
System.out.println("Queen: Up, Down, Left, Right, Diagonal, (in all 4 Directions)");
}
}
classRookimplementsChessPlayer{
publicvoidmoves(){
System.out.println("Rook: Up, Down, Left, Right");
}
}
classKingimplementsChessPlayer{
publicvoidmoves(){
System.out.println("King: Up, Down, Left, Right, Diagonal, (by 1 Step)");
}
}
// Multiple Inheritance:interfaceHerbivors{
voideat();
}
interfaceCarnivore{
voideat();
}
classBearimplementsHerbivors, Carnivore{
publicvoideat(){
System.out.println("Eat Grass And Eat Meat.");
}
}

Static Keyword::

  • Static Keyword in Java is used to Share the Same Variable Or Method of a given Class
  • Properties: Variables
  • Methods: Funtions
  • Blocks: {--Club 2-3 Lines of Code--} (Black of Code)
  • Nested Classes: Similar as Nested Loops
// Static:publicclassOOP{
publicstaticvoidmain(Stringargs[]) {
Studentstudent1 = newStudent();
student1.schoolName = "SubhedarWada";
Studentstudent2 = newStudent();
System.out.println(student2.schoolName);
System.out.println(student2.returnPercentage(12,12,12));
}
}
classStudent{
Stringname;
introllno;
// Properties:staticStringschoolName; // Methods:staticintreturnPercentage(intmath, intphy, intchem){
return(math+phy+chem)/3;
}
voidsetName(Stringname){
this.name = name;
}
StringgetName(){
returnthis.name;
}
}

Super Keyword::

  • Super keywordis used to refer Immediate Parent Class Object.
  • To Access Parent's Properties.
  • To Access Parent's Functions.
  • To Access Parent's Constructor.
// Super:publicclassOOP{
publicstaticvoidmain(Stringargs[]) {
Horsehorse = newHorse();
System.out.println(horse.color);
} }
classAnimal{
Stringcolor;
Animal(){
System.out.println("Animal Constructor Callaed");
}
}
classHorseextendsAnimal{
Horse(){
super.color = "Brown";
System.out.println("Horse Constructor Called");
}
}
  • Advanced: Constructive Chaining You can Learn.
  • End OOP's

Java -> Android, Web, Enterprise Market | Applications | Complex Web Applications | Mobile Applications | Emmbeded Softwares Language -> Syntax Cahange Basic -> Core (OOP) -> JDBC(Java Database Connectivity) -> Servelet -> Jsp -> Hybernate Framework -> Spring -> Spring Boot Java as Language: - Basic: Syntax, Cnstruct, loop, Condition, logic. - Core:- Object, Inheritance, Polymorphism, Encapsulation, Abstraction. - Advanced:- Files, Database, Multithreading. Java as Technology: Servelet, Spring Framework, Hibernate Framework IDE: Integrated Devlopment Environment -> Type - Compile - Run. In Java Every Line make Scence. Prespective: Core Java: Java Prespective | Web: Java EE (Enterprise Editor) Create: New Java Project New Package | Class

String Should be in Double Coatation: ("") Semicolan: Terminates the line: (); Block of Code: Class{}, Methods(){} Source Code: Compile: Byte Code: Java Virtual Machine Variables: Container, Memory Name, To Store Data, Primitive Data Types & Refrence Data Types: Premitive Data Types:

Data TypeKeywordSize(bit)Size(Byte)
CHarecterChar162
ByteByte81
ShortShort162
IntegerInt324
FloatFLoat324
LongLong648
DoubleDouble648
BooleanBoolean81
  • Allowed in Variable: $ _
  • Not Allowed: Start with Number
  • Decimal Numbers: By Default Double
  • To Declare Float: Mention 5.5f;
  • To Long Number: Mention 50000000000l;
  • Char ch = 'C';
  • American Standard Code For Information Interchange:
  • Implicit Convertion: Mean Java Do By Default.
    Double d1 = 5;
  • Explicit Conversion: Type Casting: Changes ForceFully Done By Us. int k = (int)5.6 Byte - Char - Short - int - long - Float - Double
  • Naming Convantion in Java: Specific Standards: Look Good, More Efficient, Readable
  • In Java We Follow Camel-Casing Rule:
  • Variable Name: sname, stockprice
  • Constant: PI, DENSITY, MAX_PRICE
  • Method: Verb : actionPerformed(), run(), print(), write()
  • Class Name: Noun : String, Integer, Student, Worker, Engineer, Person, Computer, HashMap
  • Constructor: Car(), Run(), Swim()
  • Interface Name: Adjective - able : Runable, Serializable, Remote, Readable
  • Multiline Comment: /-----/
  • Single Line Comment: //
  • Operators:
    • Arithmatic Operators:
    • Bitwise Operators:
    • Relational Operators:
    • Logical Operators:

About

📚 Learn and Master OOP Concepts in Java! This repository is a comprehensive collection of Object-Oriented Programming (OOP) examples, projects, and practice problems written in Java. Perfect for students, developers, and enthusiasts looking to sharpen their Java skills. 🖥️💡

Topics

Resources

Stars

3 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages