初识Java,
初识Java,
1.Java是一种面向对象语言,而面向对象语言有三大特性:封装、继承、多态。
2.类与对象 对象是对客观事物的抽象,类是对对象的抽象。对象是类的实例,类是对象的模板。类中有该类对象所共有的属性和方法。一个类可以创建无数个对象,一个对象只能从一个类创建/
3.对象初始化方法
(1)提供get和ste方法
class Apple{
private int weight;
private String color;
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
(2)使用构造方法
class Apple{
private int weight;
private String color;
public Apple(int weight, String color) {
this.weight = weight;
this.color = color;
}
}
在一个类中,当你没写构造方法时,系统会自动生成无参无内容的构造方法。
(3)静态代码块和实例代码块
class Apple{
private int weight;
private String color;
private static String taste;
static{
taste = "sweet";
}
{
weight = 2;
color = "red";
}
}
4.this关键字:当前对象的引用,它也可以用来调用其他构造方法(必须写在第一行)
class Apple{
private int weight;
private String color;
public Apple(){
this(2,"red");
}
public Apple(int weight, String color) {
this.weight = weight;
this.color = color;
}
}
5.static关键字修饰的属性属于类,使用类名直接调用。静态方法中不能直接调用非静态方法,但非静态方法可以直接访问静态方法(访问权限足够的情况下)。
6.内部类:可以将一个类定义在另一个类里面或者一个方法里面,这样的类称为内部类。广泛意义上的内部类一般来说包括这四种:
(1)成员内部类
class Fruit{
private int weight;
static String kind;
public Fruit(int weight, String kind) {
this.weight = weight;
this.kind = kind;
}
class Apple{
String taste;
public Apple(String taste) {
super();
this.taste = taste;
}
}
}
(2)静态内部类
(3)本地内部类:在方法中的类
(4)匿名内部类
内部类无法直接创建对象,需要通过外部类对象的引用创建
class Fruit{
private int weight;
private static String kind;
public Fruit() {
this.weight = weight;
this.kind = kind;
}
class Apple{
String taste;
public Apple() {
this.taste = taste;
}
}
}
public class Demon1 {
public static void main(String[] args) {
Fruit f = new Fruit();
Apple a = f.new Apple();
}
}
7.super关键字:使用super关键字调用父类的成员变量和成员方法,必须放在第一行。
8.继承 关键字extends 子类拥有父类的属性和普通方法,一个子类只能继承一个父类。可提高代码的复用性。
class Fruit{
int weight;
String kind;
public Fruit() {
this.weight = weight;
this.kind = kind;
}
public void Eat(){
System.out.println("eat fruit");
}
}
class Apple extends Fruit{
String taste;
public Apple() {
this.taste = taste;
}
}
9.多态:三个条件 继承、重写、父类引用指向子类对象
相关文章
- 暂无相关文章
用户点评