Class is keyword in java

Java classes and objects (with examples)

Java is a well-known object-oriented programming language used to create a variety of applications. Object-oriented programming is founded on the idea of objects, which are actual instances of classes. A class is a blueprint in Java that specifies the properties and methods of objects. Java programmers must grasp classes and objects. This post introduces Java classes and objects with examples.

A class in Java is a blueprint for creating objects. It specifies a set of attributes (or data members) and behaviors (or methods) that a class object can have. Multiple instances (or objects) of a class can be created, each with its own set of attribute values, and each object can invoke the class’s methods. As an example:

This class serves as a template for creating objects even though it lacks data members and methods. You could, for instance, do the following to make an instance of this class:

MyClass myObject = new MyClass();

«myObject» is a «MyClass» object. This object can be used as a placeholder or marker in your code despite having no attributes or behaviors. To add functionality or create subclasses, you can extend this class.

Читайте также:  Java соединение по tcp

In other words, a class develops a logical framework that establishes the relationships among its members and produces a new data type that can be used to create objects. A class instance is produced when an object of that class is declared. A class is thus a logical construct. An object occupies space in memory and has a physical reality. Any idea you want to use in a Java program needs to be contained within a class.

The class keyword in Java

The «class» keyword is used to declare or define a new class in Java. As an example:

public class MyClass < // block of code to define this class >

The new keyword in Java

The «new» keyword is used to create a new instance of a class. As an example, let’s create an instance of the previously created class named «MyClass.»

Java class and object example

Consider the following Java program as an example demonstrating the class and object.

public class ClassObjectExample < private int res; public int findSum(int a, int b) < res = a + b; return res; >public static void main(String[] args) < ClassObjectExample myObject = new ClassObjectExample(); int numOne = 10, numTwo = 20, add; add = myObject.findSum(numOne, numTwo); System.out.println("Sum of " + numOne + " and " + numTwo + " obh">Output
Sum of 10 and 20 = 30

This Java program is made up of a class called "ClassObjectExample" that has a private integer variable called "res" and a public method called "findSum" that takes two integer parameters and returns their sum. The method returns the same value as the sum of the two integers assigned to the private variable "res." The "new" keyword is used in the main method to create an object of the "ClassObjectExample" class. The variable "myObject" holds the object reference. Declare and assign values to two integer variables named "numOne" and "numTwo." The "findSum" method is invoked on the "myObject" object, with the variables "numOne" and "numTwo" as arguments. The result is saved in the variable "add." Finally, using the "System.out.println()" statement, the sum is printed to the output console.

The previous program is a very basic example demonstrating class and object in Java. Now let's level up with the following program:

public class ClassObjectExample < private String name; private int age; private String gradeLevel; public void setName(String name) < this.name = name; >public void setAge(int age) < this.age = age; >public void setGradeLevel(String gradeLevel) < this.gradeLevel = gradeLevel; >public String getName() < return name; >public int getAge() < return age; >public String getGradeLevel() < return gradeLevel; >public static void main(String[] args) < ClassObjectExample student1 = new ClassObjectExample(); student1.setName("William"); student1.setAge(16); student1.setGradeLevel("Junior"); ClassObjectExample student2 = new ClassObjectExample(); student2.setName("Edwin"); student2.setAge(17); student2.setGradeLevel("Senior"); System.out.println(student1.getName() + " is a " + student1.getGradeLevel() + " in high school and is " + student1.getAge() + " years old."); System.out.println(student2.getName() + " is a " + student2.getGradeLevel() + " in high school and is " + student2.getAge() + " years old."); >>
William is a Junior in high school and is 16 years old. Edwin is a Senior in high school and is 17 years old.

This program defines "ClassObjectExample" as a class with three private instance variables: "name", "age", and "gradeLevel." These variables are encapsulated within the class, which restricts their access and modification to the class's public methods. The class also contains six public methods, including three setter methods (setName, setAge, and setGradeLevel) to set the instance variables' values and three getter methods (getName, getAge, and getGradeLevel) to retrieve them.

Two instances of the "ClassObjectExample" class are created in the program's main method, one for each student. These objects are created using the "new" keyword. The values of the objects' instance variables are set using the setter methods after they have been created. Following the values' retrieval using getter methods, System.out.println statements are used to print them to the output console.

Advantages of classes in Java

  • Encapsulation: Java classes enable encapsulation, which allows the implementation specifics of a class to be shielded from other program elements. This enhances the code's security and maintainability.
  • Reusability: Classes encourage the reuse of code. A class can be used to create any number of objects with the same properties and behaviors once it has been defined. Coding becomes easier and more efficient as a result.
  • Java supports inheritance, allowing new classes to be based on existing classes and to inherit their properties and methods. This can make the code more extensible and modular by reducing code duplication.
  • Java supports polymorphism, a feature that enables objects of various classes to be handled as though they were objects of the same class. The code could become more flexible and cleaner as a result.

Disadvantages of classes in Java

  • Complexity: Classes, particularly those that are poorly made or applied improperly, can add complexity to a program. This could make it more challenging to read, maintain, and debug the code.
  • Overhead: When creating a class, some processing and memory costs are incurred. This might be a problem on devices with limited resources or in performance-critical applications.
  • Lack of extensibility: If classes are not intended to be extensible, they may lack flexibility. It can be challenging to change a class after it has been defined without having an impact on other program elements.
  • Learning curve: For newcomers, understanding classes can be challenging. Procedural programming requires a different way of thinking than object-oriented programming, which can take some practice to master.

Liked this article? Share it!

Источник

What is class in Java

Java is an object oriented programming language. Classes and objects are the key concepts to understand object oriented programming. Java programming is based on these two terms. Let's understand what a class means in this tutorial and we will discuss about objects in next tutorial.

Programmatically a class is a group of variables, constructors, methods, blocks etc. These are optional components of a class. A class is defined using class keyword followed by class name. The name of the class is used to refer that class within or outside the class. The basic syntax of declaring a class is :

class ClassName < // variables, constructors, // method declarations >

Here class is a keyword, used to define a class in java. ClassName is the name of class, given by the programmer. After the class name, it's the class body given inside < >. Variables, methods, constructors etc defined inside the balanced < >after the class name are the part of that class.

Do we have any convention to write the class name ?

The convention is that the class name and any subsequent word in class name should start with upper case, for example MyFirstProgram, HelloWorldProgram, Person, Bicycle etc are valid class names of this convention.

Is class keyword case-sensitive ?

All keywords in java are case-sensitive and they must be in small letter. So you can not use class keyword as Class, CLASS, clAss etc, it must be in small letters.

In object oriented world, think of a class as a blueprint or a design that basically describes how an object of a class will behave and what data(properties) it will contain inside it. The methods of a class defines the behavior of object while instance variables are the data of the object that it will contain inside.

Real time example of class

Some of the real world examples of class are Person, Vehicle, House, Tree, Dog etc. For an example a Person class have properties like name, age, height etc. and behaviors like walk, talk, eat, sleep etc. Now if you create an object of this class, it will have these properties and behaviors inside it. Once you created a class, you can create multiple objects of that class.

real world example of class

Can I give any name to my class ?

Yes, you can give any name to your class by following the identifier naming convention rules but giving a meaningful name is a good programming style. For example class names like Abc , XYZ are valid names but not meaningful names while class names like MyFirstProgram, HelloWorldProgram, Person are meaningful names.

Java Class Program

 class Person < // Instance variables, describes state/properties of object of this class. String name; int age; int height; // methods, describes behaviors of object of this class. public void walk() < System.out.println("Hi my name is : "+name+", age : "+age+" year," +" height : "+height+" cm. I can Walk"); > public void talk() < System.out.println("Hi my name is : "+name+", age : "+age+" year," +" height : "+height+" cm. I can Talk"); > > class ClassDemo < public static void main(String [] args) < Person p1 = new Person(); // Creating object of class Person p1.name = "Rahul"; p1.age = 20; p1.height = 170; p1.walk(); p1.talk(); > >

Save above program as ClassDemo.java
compile as javac ClassDemo.java
run as java ClassDemo

Hi my name is : Rahul, age : 20 year, height : 170 cm. I can Walk
Hi my name is : Rahul, age : 20 year, height : 170 cm. I can Talk

In above example we have created a class called Person which is basically a prototype, describing that object of this class will have properties as name, age, height and will have behaviors as walk and talk . You can add more properties(instance variables) and behaviors(methods) in your program. This example creates only a single object of Person class. You can create multiple objects of Person class and assign different values inside it.

Should I create all classes in single file ?

No, that's not a good programming style. In real world programming mostly we use to create each classes in separate files in our application.

So next time when you are creating a class, think that you are creating a prototype which will tell that what properties(state) and behaviors will exist inside the object of that class. This way you will get better idea to design your class.

A class is also called as a blueprint or a template or a design or a Type . These are just different words use to describe a class in java.

Who loads java classes in memory while execution ?

As soon as you run a program, the class-loaders available in java virtual machine loads classes in memory for execution. In java, these class-loaders are also a program.

Is it mandatory to define variables(instance or static variable) on top of a class ?

No, you can define such variables after the method or in end of a class but that's not a good programming style. You should always prefer to declare it at top since it makes a class more readable.

Can a class exist without main method ?

Yes, in real world programming only the starting class of your application(a group of classes) will have main method, all other classes won't have main method.

Should I focus more on real world aspect of class ?

As a programmer you should focus more on it's programming aspect rather than focusing on real world aspect, programming aspects like creation of class, creation of variables and methods inside the class, creation of objects of class etc.

The syntax of declaring a class given in this tutorial is the minimal one which is required. Some of the more keywords that can be declared along with class keyword are public, abstract, final, extends, implements . A class can also have another class, static blocks, enum etc inside the body of it. We will discuss all these things in later tutorials.

  • Every program must have at least one class, it can have more than one class as well.
  • If there are multiple classes in a single program file, the file must be saved by class name declared with public keyword, if any.
  • Every class(user defined or defined by java) in java is a non primitive data type.
  • There should be only one main method having argument type as String [] in a class.
  • If there are multiple non public classes in a single program file, conventionally the program file should be saved by class name having main method.

Источник

Оцените статью