Class in Java
A class in Java is a blueprint from which individual objects are created. It can contain fields and methods to describe the behavior of an object.
public class Car {
String color;
String model;
void displayDetails() {
System.out.println("Model: " + model + ", Color: " + color);
}
}
Object in Java
An object is an instance of a class. It is created using the new keyword and can access the fields and methods defined in the class.
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.color = "Red";
myCar.model = "Tesla Model S";
myCar.displayDetails();
}
}
Object Creation Using new Operator in Java
To create an object in Java, you use the new operator followed by the class name. For example:
Car myCar = new Car();
Object class in Java
The Object class is the parent class of all classes in Java. It provides common methods like equals(), hashCode(), and toString().
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
System.out.println(myCar.toString());
}
}
Type Wrapper Classes in Java
Wrapper classes provide a way to use primitive data types (int, boolean, etc.) as objects. Examples include Integer, Boolean, and Double.
Integer myInt = 5;
Double myDouble = 5.99;
Boolean myBool = true;
Java Abstract Class and Abstract Method
An abstract class cannot be instantiated and may contain abstract methods, which are methods without a body that must be implemented by subclasses.
abstract class Animal {
abstract void makeSound();
}
class Dog extends Animal {
void makeSound() {
System.out.println("Bark");
}
}
Java Nested Class And Inner Class
A nested class is a class defined within another class. An inner class is a non-static nested class that has access to the members of its enclosing class.
class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
}
}
Java Object Cloning - clone() Method
Object cloning is a way to create an exact copy of an object. The clone() method is used to create a copy of an object.
class Car implements Cloneable {
String model;
String color;
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Shallow Copy And Deep Copy in Java Object Cloning
Shallow copy copies the object's fields as they are, while deep copy creates a new instance of each field. Deep copy is more thorough but also more complex.
// Shallow Copy Example
class Car implements Cloneable {
String model;
Engine engine;
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
// Deep Copy Example
class Car implements Cloneable {
String model;
Engine engine;
public Object clone() throws CloneNotSupportedException {
Car cloned = (Car) super.clone();
cloned.engine = new Engine(engine.type);
return cloned;
}
}