一、类,Java跟C和C++不同,类是基本的构成要素,所有对象都是由类创建的。
类的声明格式 :[修饰符] class [类名] [extends 父类名] [implements 接口名]
extends和implements项均为可选,表示是否继承或是否实现接口,修饰符可选值为(1)public:表明该类可悲其他类访问和引用,(2)abstract:表明该类只生命方法的存在而不去实现它,(3)final:该类不能被继承。
二、继承
首先是一个简单的类Fruit,有一个成员变量color和构造函数和一个成员函数im。
public class Fruit {
String color;
public Fruit()
{
color = "no color";
}
public void im()
{
System.out.println("I am fruit");
}
}
然后一个类Apple继承Fruit
public class Apple extends Fruit{
public Apple()
{
color = "red";
}
public void im()
{
System.out.println("I am an apple");
}
public void getColor()
{
System.out.println("red");
}
public static void main(String[] args)
{
Apple apple = new Apple();
apple.getColor();
apple.im();
}
}
运行后结果为
red
I am an apple
三、this关键字
用在类的成员函数里面,局部变量和成员变量的名字相同时,成员函数就会被隐藏,这时如果想用成员变量,则必须使用关键字this。
public class Fruit {
String color;
public Fruit()
{
color = "green";
}
public void im()
{
System.out.println("I am fruit");
}
public void harvest()
{
String color = "red";
System.out.println("color in the member function:" + color);
System.out.println("color in the class Fruit is:" + this.color);
}
public static void main(String[] args)
{
Fruit fruit = new Fruit();
fruit.harvest();
}
}
运行结果是
color in the member function:red
color in the class Fruit is:green
四、super关键字
用在继承了父类的子类,想在子类中访问父类中被子类隐藏的成员方法或变量时,用super关键字调用父类的im函数和getColor
PS:super关键字不能再static的函数里面用。
public class Apple extends Fruit{
public Apple()
{
color = "red";
}
public void im()
{
super.im();
}
public String getColor()
{
String str = super.getColor();
return str;
}
public static void main(String[] args)
{
Apple apple = new Apple();
apple.im();
System.out.print("The color is :" + apple.getColor());
}
}
运行结果是
I am fruit
The color is :green
五、总结:
总体来说,Java的类感觉跟C++还是差不多的,我认为的主要区别有:
1、执行的函数main函数要写在类里面,并且要使用类的函数或是成员变量的时候需要实例化一个类,否则不能用。
2、Java用类实例化一个对象,需要用new,比如:Apple apple = new Apple(),而C++是Apple apple即可。
3、Java的类有修饰符,如public、abstract、final这些,而C++类是没有的,就像默认都是public的Java的类。
4、Java的类可以直接在成员变量上初始化,而C++则要是在构造函数中完成。不过我自己试了一下,C++中给类的成员变量直接赋值是可以的,只是会出现warning,然后说C++11中才支持这样的操作。