Introduction Java is an object-oriented programming language. Classes and objects are fundamental concepts in Java.
Class definition Class head class name_of_class . Class body { data members; member functions; };
E xample public class Car { // Fields (variables) String color; String model; int year;
What is a Class? A class is a blueprint for creating objects . It defines a datatype by bundling data and methods that operate on the data into a single unit.
Introduction to objects Object is an abstraction of real world entity. Objects are the variables/instances of classes. Syntax for declaring objects is as follows : Person person = new Person("Alice", 30);
What is an Object ? An object is an instance of a class. It has state (fields) and behavior (methods).
Characteristics of objects: It can have its own copy of data members. The scope of an object is determined by the place in which the object is defined. It can be passed to a function like normal variables. The members of the class can accessed by the object using the object to member access operator or dot operator(.).
Access Modifiers public: Accessible from anywhere . private : Accessible only within the class . protected : Accessible within the same package and subclasses . default (no modifier): Accessible within the same package.
Example: public class Dog { String name ; void bark() { System.out.println (name + " says Woof!"); } }
Example: public class Main { public static void main(String[] args ) { // Declare and create an object of the Dog class Dog myDog = new Dog(); // Set the name field myDog.name = "Buddy"; // Call the bark method myDog.bark (); } }
Conclusion Classes and objects are core components of Java's object-oriented programming. Mastering these concepts is crucial for effective Java programming.