About Static keyword and new keyword

Static keyword:

  • Static keyword belongs to class which includes class specific information.
  • A static method(tbd) is also called a class method and is common across the objects of the class and this method can be accessed using class name as well.
  • A static method can call only other static methods; it cannot call a non-static method
  • A static method can be called directly from the class
  • Since the static method refers to the class, the syntax to call or refer to a static method is: class name.method name
  • Static keyword is used in java mainly for memory allocation.
Static keyword in Java - Javatpoint

Non static method:

  • Any method of a class which is not static is called non-static method or an instance method.
  • A non-static method can access both static as well as non-static members.
  • A non-static method in Java belongs to the object of a class

new – keyword in java:

  • new keyword is used while creating object
  • It allocates unique memory for object
  • We can also use the new keyword to create the array object.

Example:

Shop prod1 = new Shop;
//prod1= newly created object

The new keyword in Java programming language - Codeforcoding
The new keyword in Java programming language - Codeforcoding

program:

public class Shop{
	String name;
	int price;
	static String shopName="cosmetics";
	static String doorNo="35";
public static void main(String[]args){
Shop prod1 = new Shop();
	prod1.name="soap";
	prod1.price=10;
Shop prod2 = new Shop();
	prod2.name="rice";
	prod2.price=50;
Shop prod3 = new Shop();
	prod3.name="wheat";
	prod3.price=40;
System.out.println(prod2.name);
System.out.println(prod3.price);
	System.out.println(Shop.shopName);
	System.out.println(Shop.doorNo);
	

}}

Errors:

Error 1

oem@Root:~/Documents/B19$ javac Shop.java
Shop.java:20: error: non-static variable name cannot be referenced from a static context
System.out.println(name);
^
1 error

Error 2:

Error 3:

Error 4:

References:

Static vs non static : 1. https://www.tutorialspoint.com/differences-between-static-and-non-static-methods-in-java

Static vs non static: 2. https://study.com/academy/lesson/static-vs-non-static-methods-in-java.html

New keyword: https://youtu.be/Vb4VEFM6OJ4

Leave a comment

Design a site like this with WordPress.com
Get started