Class and Objects
Class is a blueprint.
An object is a real entity.
NOTE : Don't confuse with these names they all same meaning
States = attributes = properties
Behavior = functions/methods
package practiceJava;
//Car class definition
class Car {
// Properties
private String color;
private String model;
private double kilometers;
// Constructor (initialize properties)
public Car(String color, String model) {
this.color = color;
this.model = model;
this.kilometers = 0.0; // Initialize kilometers to zero
}
// Methods
public void start() {
System.out.println("Car engine started.");
}
public void stop() {
System.out.println("Car engine stopped.");
}
public void drive(double distance) {
kilometers += distance;
System.out.println("Car driven " + distance + " km. Total kilometers: " + kilometers);
}
public void reverse(double distance) {
kilometers -= distance;
System.out.println("Car reversed " + distance + " km. Total kilometers: " + kilometers);
}
public static void main(String[] args) {
// Create a car object
Car myCar = new Car("Red", "Toyota");
// Perform actions
myCar.start();
myCar.drive(50.5);
myCar.reverse(10.2);
myCar.stop();
}
}
output
Car engine started.
Car driven 50.5 km. Total kilometers: 50.5
Car reversed 10.2 km. Total kilometers: 40.3
Car engine stopped.
constructor
What is a Constructor?
A constructor in Java is a special method used to initialize objects.
It is called when an instance (object) of a class is created.
Constructors allow us to set initial values for object attributes.
Key Points about Constructors:
Constructors have the same name  as the class they belong to.
They do not have a return type (not even
void
).Constructors are called automatically when an object is created using the
new
keyword.If you don’t define any constructors, Java provides a default constructor (with no arguments) for your class.
Types of Constructors:
Default Constructor: No arguments, provided by Java if not explicitly defined.
Parameterized Constructor: Accepts arguments to initialize object properties.
Copy Constructor: Creates a new object by copying values from an existing object.
Example
package practiceJava;
class Car {
private String make;
private String model;
// Parameterized constructor
public Car(String make, String model) {
this.make = make;
this.model = model;
}
// Copy constructor
public Car(Car otherCar) {
this.make = otherCar.make; // Copy make
this.model = otherCar.model; // Copy model
}
public void displayInfo() {
System.out.println("Make: " + make);
System.out.println("Model: " + model);
}
public static void main(String[] args) {
// Create an original car
Car originalCar = new Car("Tata", "safari");
// Create a copy using the copy constructor
Car copiedCar = new Car(originalCar);
// Display info for both cars
System.out.println("Original Car:");
originalCar.displayInfo();
System.out.println("\nCopied Car:");
copiedCar.displayInfo();
}
}
Output
Original Car:
Make: Tata
Model: safari
Copied Car:
Make: Tata
Model: safari
Types of variables/methods
Static variables and methods
Static variables (also known as class variables) are associated with the class itself, not with any specific instance (object) of the class.
They are declared using the
static
keyword.There is only one copy of a static variable shared among all instances of the class.
Static variables are initialized when the class is loaded into memory and exist throughout the program’s execution.
Non-Static (Instance) Variables:
Instance variables are specific to each instance (object) of the class.
They are declared without the
static
keyword.Each object has its own copy of instance variables.
Instance variables are initialized when an object is created and exist as long as the object is in memory.
Local Variables:
Local variables are declared within a method, constructor, or block.
They are temporary and exist only within the scope where they are defined.
package practiceJava;
public class Student {
// Static variable
static String schoolName = "ABC High School";
// Non-static variables
String studentName;
int grade;
public Student(String name, int grade) {
this.studentName = name;
this.grade = grade;
}
public void printMessage() {
String message = "Hello!"; // Local variable
System.out.println(message);
}
public void displayInfo() {
System.out.println("School Name: " + schoolName);
System.out.println("Student Name: " + studentName);
System.out.println("Grade: " + grade);
}
public static void main(String[] args) {
Student student1 = new Student("mr kk", 10);
Student student2 = new Student("mr rk", 11);
student1.displayInfo();
student2.displayInfo();
student2.printMessage();
}
}
this -
used to refer current class instance variableoutput
School Name: ABC High School
Student Name: mr kk
Grade: 10
School Name: ABC High School
Student Name: mr rk
Grade: 11
Hello!
example for static method
class Helper {
public static int sum(int a, int b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
int n = 3, m = 6;
int s = Helper.sum(n, m);
System.out.println("Sum is = " + s);
}
}
example for non static method (instance method)
class Helper {
public int sum(int a, int b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
int n = 3, m = 6;
Helper g = new Helper();
int s = g.sum(n, m);
System.out.println("Sum is = " + s);
}
}
Encapsulation
Encapsulation promotes data hiding and protects the internal details of a class from external access. It allows you to bundle data (variables) and methods (functions) together into a single unit, ensuring that the implementation details are hidden from other classes.
example,
Two class, one is
Bank
and another one isCustomer
Rules,
customer can only view the minimum balance.
not allow to edit
minimumBalance
if they enter less than 2500.
public static class Bank {
public static String bankName = "Reserve bank";
private int minimumBalance = 2500;
public int getMinimumBalance() {
return minimumBalance;
}
public void setMinumBalance(int minBal) {
if (minBal >= 2500) {
this.minimumBalance = minBal;
}
else {
System.out.println("not allowed to set minimum balance less than 2500");
}
}
}
public static class Customer {
public static void main(String[] args) {
Bank customerA = new Bank();
int minbal = customerA.getMinimumBalance();
System.out.println("minimum balance :" + minbal);
customerA.setMinumBalance(2400);
}
}
Inheritance
subclass (child)
superclass (parent)
To inherit from a class, use the extends
keyword.
Types of Inheritance:
Single Inheritance: single parent and single child
Multilevel Inheritance: (Grand child)
Hierarchical Inheritance: single parent multiple child's.
Multiple Inheritance (Not Supported in Java): Multiple parents. can achieve using interface.
multiple inheritance, example
protected access modifier
- anyone can access if same package
- if other package child can only able to access.
class Animal {
void eat() {
System.out.println("Animal is eating.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking.");
}
}
Polymorphism
Polymorphism means "many forms".
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
}
class Dog extends Animal {
public void animalSound() {
System.out.println("The dog says: bow wow");
}
}
Abstraction
Data abstraction is the process of hiding certain details and showing only essential information to the user
use abstract
- to declare.
Note: if one method is abstract then class should declare as abstract.
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}
// Subclass (inherit from Animal)
class Pig extends Animal {
@Override
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Interface
An interface
is a completely "abstract class" that is used to group related methods with empty bodies
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
String
In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
same as
String s="javatpoint";
https://www.w3schools.com/java/java_ref_string.asp